diff --git a/src/3rdParty/libE57Format/CHANGELOG.md b/src/3rdParty/libE57Format/CHANGELOG.md index 30c083bcbfaa9..ded79ef373a6b 100644 --- a/src/3rdParty/libE57Format/CHANGELOG.md +++ b/src/3rdParty/libE57Format/CHANGELOG.md @@ -1,16 +1,163 @@ # Changelog -All notable changes to this project will be documented in this file. +All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). +## 3.1.0 - (in progress) -## 2.2.1 - (in progress) +### Added + +- {cmake} New option `E57_RELEASE_LTO` controls whether link-time optimization is on for release builds. It defaults to `ON`. ([#254](https://github.com/asmaloney/libE57Format/pull/254)) + + CMake forces "thin" LTO (see [this issue](https://gitlab.kitware.com/cmake/cmake/-/issues/23136)) which is a problem if compiling statically for distribution (e.g. in a package manager). Generally you will only want to turn this off for distributing static release builds. + +### Changed + +- {cmake} Remove `E57_VISIBILITY_HIDDEN` option. ([#259](https://github.com/asmaloney/libE57Format/pull/259)) + + I cannot get extern templates to work across all of gcc, clang, apple clang, and MSVC when using "hidden" visibility with shared libraries. + +### Fixed + +- Fix clang warnings about implicit conversions in _SourceDestBufferImpl.cpp_. Apple's clang doesn't warn about these, but it looks like the official clang releases do. ([#257](https://github.com/asmaloney/libE57Format/pull/257)) (Thanks Martin!) + +## [3.0.2](https://github.com/asmaloney/libE57Format/releases/tag/v3.0.2) - 2023-07-22 + +### Fixed + +- Fix `E57_VERBOSE` build. ([#251](https://github.com/asmaloney/libE57Format/pull/251)) (Thanks Jia!) +- {standard conformance} Fix invalid range exception in FloatNode implementation. ([#250](https://github.com/asmaloney/libE57Format/pull/250)) +- Fix reading of index packets. ([#249](https://github.com/asmaloney/libE57Format/pull/249)) +- Fix several places where we should be checking for MSVC, not WIN32. ([#248](https://github.com/asmaloney/libE57Format/pull/248)) +- Fix "unnecessary semicolons" warnings which prevented building with GCC <= 10. ([#241](https://github.com/asmaloney/libE57Format/pull/241)) (Thanks Andre!) + +## [3.0.1](https://github.com/asmaloney/libE57Format/releases/tag/v3.0.1) - 2023-03-15 + +### Added + +- {ci} Added an MSVC 32-bit build. ([#235](https://github.com/asmaloney/libE57Format/pull/235)) + +### Fixed + +- {cmake} Turn off inter-procedural optimization in debug builds. Link-time optimization can make debugging more difficult. ([#240](https://github.com/asmaloney/libE57Format/pull/240)) +- {cmake} Don't force a debug postfix if `CMAKE_DEBUG_POSTFIX` is defined.([#239](https://github.com/asmaloney/libE57Format/pull/239)) +- {cmake} Don't force install locations. This prevents overriding them using `CMAKE_INSTALL_BINDIR` & `CMAKE_INSTALL_LIBDIR`.([#237](https://github.com/asmaloney/libE57Format/pull/237)) +- Fix warnings which prevented building on 32-bit systems. ([#233](https://github.com/asmaloney/libE57Format/pull/233), [#234](https://github.com/asmaloney/libE57Format/pull/234)) + +## [3.0.0](https://github.com/asmaloney/libE57Format/releases/tag/v3.0.0) - 2023-02-23 + +There have been _many_ changes around the `Simple API` in this release to fix some problems, avoid potential errors, and simplify the use of the API. Where possible these changes are marked as `deprecated` to be removed later. The compiler will produce warnings for these indicating what needs to change. Other changes could not be marked deprecated but will break the API, requiring code changes. The notable ones are marked with 🚧 below. + +### Added + +- Add address (ASan) and undefined behaviour (UBSan) sanitizers. These are controlled by `E57FORMAT_SANITIZE_ALL`, `E57FORMAT_SANITIZE_ADDRESS` and `E57FORMAT_SANITIZE_ADDRESS`. They are not included when building with MSVC. +- Add new `E57Version.h` header for more convenient access to version information. ([#197](https://github.com/asmaloney/libE57Format/pull/197)). +- Add `ImageFile::extensionsLookupPrefix()` overload for more concise user code. ([#161](https://github.com/asmaloney/libE57Format/pull/161)) +- Added a constructor & destructor for **E57SimpleData**'s `Data3DPointsData_t`. This will create all the required buffers based on an `e57::Data3D` struct and handle their cleanup. See the `SimpleWriter` tests for examples. ([#149](https://github.com/asmaloney/libE57Format/pull/149)) + + > **Note:** I strongly recommend these new constructors be used to simplify your code and help prevent errors. + +- A new **E57SimpleReader** constructor takes a `ReaderOptions` struct which allows setting the checksum policy. + ```cpp + Reader( const ustring &filePath, const ReaderOptions &options ); + ``` +- {test} Added testing using [GoogleTest](https://github.com/google/googletest). For details, please see [test/README.md](test/README.md) ([#121](https://github.com/asmaloney/libE57Format/pull/121)) +- Added `E57Exception::errorStr()` to get the error string directly. ([#128](https://github.com/asmaloney/libE57Format/pull/128)) +- {cmake} Use [ccache](https://ccache.dev/) if available. ([#129](https://github.com/asmaloney/libE57Format/pull/129)) +- {ci} Added a CI check for proper clang-formatted code. ([#125](https://github.com/asmaloney/libE57Format/pull/125)) + +### Changed + +- Now requires a **[C++14](https://en.cppreference.com/w/cpp/14)** compatible compiler. +- Now requires **[CMake](https://cmake.org/) >= 3.15**. ([#205](https://github.com/asmaloney/libE57Format/pull/205)) +- 🚧 **DEBUG** and **VERBOSE** macros were changed to simplify and clarify: + - New `E57_ENABLE_DIAGNOSTIC_OUTPUT` controls the inclusion of the code for the `dump()` functions on nodes. I don't see any real reason to turn this off, but I left the capability in for compatibility. + - New `E57_VALIDATION_LEVEL=N` replaces `E57_DEBUG` (N=1) and `E57_MAX_DEBUG` (N=2). + - `E57_MAX_VERBOSE` was consolidated with `E57_VERBOSE` since they were essentially the same. +- When building itself, warnings are now treated as errors. ([#205](https://github.com/asmaloney/libE57Format/pull/205), [#211](https://github.com/asmaloney/libE57Format/pull/211)) +- Clean up global const and enum names to use the `e57` namespace and avoid repetition. ([#176](https://github.com/asmaloney/libE57Format/pull/176)) + - i.e. instead of `e57::E57_STRUCTURE`, we now use `e57::TypeStructure` +- {format} Update clang-format rules for clang-format 15. ([#168](https://github.com/asmaloney/libE57Format/pull/168), [#179](https://github.com/asmaloney/libE57Format/pull/179)) +- Change default checksum policies to an enum. ([#166](https://github.com/asmaloney/libE57Format/pull/166)) + Old | New + --|-- + CHECKSUM_POLICY_NONE | ChecksumPolicy::None + CHECKSUM_POLICY_SPARSE | ChecksumPolicy::Sparse + CHECKSUM_POLICY_HALF | ChecksumPolicy::Half + CHECKSUM_POLICY_ALL | ChecksumPolicy::All +- Avoid implicit conversion in constructors. ([#135](https://github.com/asmaloney/libE57Format/pull/135)) +- Update [CRCpp](https://github.com/d-bahr/CRCpp) to 1.2. ([#130](https://github.com/asmaloney/libE57Format/pull/130)) +- **E57Exception** changes ([#118](https://github.com/asmaloney/libE57Format/pull/118)): + - mark methods as `noexcept` + - use `private` instead of `protected` +- Rename **E57Simple**'s `Data3DPointsData` and `Data3DPointsData_d` structs to `Data3DPointsFloat` and `Data3DPointsDouble` respectively. ([#180](https://github.com/asmaloney/libE57Format/pull/180)) +- 🚧 **E57Simple:** Specifying the node type for cartesian & spherical points, time stamp, and intensity is now explicit using new fields (`pointRangeNodeType`, `angleNodeType`, `timeNodeType`, and `intensityNodeType`) and a new enum (`NumericalNodeType`). ([#178](https://github.com/asmaloney/libE57Format/pull/178)) + - For examples, please see _test/src/testSimpleWriter.cpp_. +- Simplify the **E57SimpleWriter** API with `WriteImage2DData()` for images and `WriteData3DData()` for 3D data. This reduces code, hides complexity, and avoids potential errors. ([#171](https://github.com/asmaloney/libE57Format/pull/171)) + - As part of this simplification, `WriteData3DData()` will now fill in any missing min/max values for cartesian & spherical points, intensity, and time stamps by looking at the data.([#175](https://github.com/asmaloney/libE57Format/pull/175)) +- 🚧 **E57Simple:** Intensity now uses `double` instead of `float`. ([#178](https://github.com/asmaloney/libE57Format/pull/178)) +- 🚧 **E57Simple:** Colours now use `uint16_t` instead of `uint8_t`. ([#167](https://github.com/asmaloney/libE57Format/pull/167)) +- 🚧 Change **E57SimpleData**'s Data3D field name from `pointsSize` to `pointCount`. ([#164](https://github.com/asmaloney/libE57Format/pull/164)) +- 🚧 Min/max fields in **E57SimpleData**'s Data3D's point fields were a mix of floats and doubles. Since the fields are doubles, set them all to doubles and use the new `Data3DPointsData_t` constructor to set them properly for floats. ([#153](https://github.com/asmaloney/libE57Format/pull/153)) + > **Note:** If you were previously relying on these to be floats and are not using the new `Data3DPointsData_t` constructor, you will need to set these. +- 🚧 Renamed the [E57_EXT_surface_normals](http://www.libe57.org/E57_EXT_surface_normals.txt) extension's fields in **E57SimpleData**'s `PointStandardizedFieldsAvailable` to be in line with existing code. ([#149](https://github.com/asmaloney/libE57Format/pull/149)) + - `normalX` renamed to `normalXField` + - `normalY` renamed to `normalYField` + - `normalZ` renamed to `normalZField` + +### Deprecated + +- `e57::Utilities::getVersions()`. ([#197](https://github.com/asmaloney/libE57Format/pull/197)) +- `e57::Data3DPointsData` and `e57::Data3DPointsData_d` types. ([#180](https://github.com/asmaloney/libE57Format/pull/180)) +- Many global const and enum names. The compiler will produce warnings including the replacement symbols (note that enumerators will not produce warnings on C++14, but they will on C++17). ([#176](https://github.com/asmaloney/libE57Format/pull/176)) +- `e57::Writer::NewImage2D`and `e57::Writer::SetUpData3DPointsData`. ([#171](https://github.com/asmaloney/libE57Format/pull/171)) +- Old default checksum policies (`CHECKSUM_POLICY_NONE`, `CHECKSUM_POLICY_SPARSE`, `CHECKSUM_POLICY_HALF`, and `CHECKSUM_POLICY_ALL`). ([#166](https://github.com/asmaloney/libE57Format/pull/166)) +- The old `e57::Reader` constructor taking only `filePath`. ([#139](https://github.com/asmaloney/libE57Format/pull/139)) +- The old `e57::Writer` constructor taking only `filePath`. ([#117](https://github.com/asmaloney/libE57Format/pull/117)) ### Fixed +- Fix several potential divide-by-zero cases. ([#224](https://github.com/asmaloney/libE57Format/pull/224)) +- {ci} Now builds shared library versions as well. ([#219](https://github.com/asmaloney/libE57Format/pull/219)) +- {win} Fixes shared library build warnings. ([#215](https://github.com/asmaloney/libE57Format/pull/215), [#216](https://github.com/asmaloney/libE57Format/pull/216), [#217](https://github.com/asmaloney/libE57Format/pull/217)) +- Fix the code which shortens floating point numbers when converted to strings. The impact of it being incorrect was negligible since it's just the floating point representation in the XML portion of the file. ([#214](https://github.com/asmaloney/libE57Format/pull/214)) +- Turned on a lot of compiler warnings and fixed them. ([#201](https://github.com/asmaloney/libE57Format/pull/201), [#202](https://github.com/asmaloney/libE57Format/pull/202), [#203](https://github.com/asmaloney/libE57Format/pull/203), [#204](https://github.com/asmaloney/libE57Format/pull/204), [#205](https://github.com/asmaloney/libE57Format/pull/205), [#207](https://github.com/asmaloney/libE57Format/pull/207), [#209](https://github.com/asmaloney/libE57Format/pull/209)) +- Fix writing floating point numbers when `std::locale::global` is set. ([#174](https://github.com/asmaloney/libE57Format/pull/174)) +- E57XmlParser: Parse doubles in a locale-independent way. ([#173](https://github.com/asmaloney/libE57Format/pull/173)) (Thanks Hugal31!) +- E57SimpleReader: Ensure scaled integer fields are set as best we can when reading. ([#158](https://github.com/asmaloney/libE57Format/pull/158)) +- Fix the [E57_EXT_surface_normals](http://www.libe57.org/E57_EXT_surface_normals.txt) extension's URI in **E57SimpleWriter**. ([#143](https://github.com/asmaloney/libE57Format/pull/143)) +- {win} Fix conversion warning when compiling with debug on. ([#124](https://github.com/asmaloney/libE57Format/pull/124)) +- Add errno detail to `E57_ERROR_OPEN_FAILED` exception. ([#119](https://github.com/asmaloney/libE57Format/pull/119), [#120](https://github.com/asmaloney/libE57Format/pull/120)) + +## [2.3.0](https://github.com/asmaloney/libE57Format/releases/tag/v2.3.0) - 2022-10-04 + +### Added + +- {cmake} Added `E57_VISIBILITY_HIDDEN` option to control [CXX_VISIBILITY_PRESET](https://cmake.org/cmake/help/latest/prop_tgt/LANG_VISIBILITY_PRESET.html). Defaults to `ON`. ([#104](https://github.com/asmaloney/libE57Format/pull/104)) (Thanks Nigel!) +- Added BSD support. ([#99](https://github.com/asmaloney/libE57Format/pull/99)) (Thanks Christophe!) + +### Changed + +- Updated & reorganized the [online API docs](https://asmaloney.github.io/libE57Format-docs/) and changed to a [cleaner theme](https://github.com/jothepro/doxygen-awesome-css). +- Change file creation to use _0666_ permissions on [POSIX](https://en.wikipedia.org/wiki/POSIX) systems. ([#105](https://github.com/asmaloney/libE57Format/pull/105)) (Thanks Nigel!) +- {cmake} [CXX_VISIBILITY_PRESET](https://cmake.org/cmake/help/latest/prop_tgt/LANG_VISIBILITY_PRESET.html) is now set and `ON` by default. ([#104](https://github.com/asmaloney/libE57Format/pull/104)) (Thanks Nigel!) +- A new **E57SimpleWriter** constructor takes a `WriterOptions` struct which allows setting the file's GUID. + ```cpp + Writer( const ustring &filePath, const WriterOptions &options ); + ``` + The old constructor taking only `coordinateMetadata` is deprecated and will be removed in the future. ([#96](https://github.com/asmaloney/libE57Format/pull/96)) (Thanks Nigel!) +- Change `E57_DEBUG`, `E57_MAX_DEBUG`, `E57_VERBOSE`, `E57_MAX_VERBOSE`, `E57_WRITE_CRAZY_PACKET_MODE` from **#defines** to cmake options. ([#80](https://github.com/asmaloney/libE57Format/pull/80)) (Thanks Nigel!) + +### Fixed + +- Fix **E57SimpleWriter**'s writing of invalid quaternions. It now defaults to the identity quaternion. ([#108](https://github.com/asmaloney/libE57Format/pull/108)) (Thanks Nigel!) +- Fix **E57SimpleReader** to handle missing `images2D` and `isAtomicClockReferenced` nodes. ([#90](https://github.com/asmaloney/libE57Format/pull/90)) (Thanks Olli!) +- Fix **BitpackIntegerDecoder** sometimes reading past end of input buffer. ([#87](https://github.com/asmaloney/libE57Format/pull/87)) (Thanks Nigel!) +- Fix compilation when some debug options are set. ([#81](https://github.com/asmaloney/libE57Format/pull/81), [#82](https://github.com/asmaloney/libE57Format/pull/82), [#84](https://github.com/asmaloney/libE57Format/pull/84)) (Thanks Nigel!) - Fix compilation with [musl libc](https://musl.libc.org/) ([#70](https://github.com/asmaloney/libE57Format/pull/70)) (Thanks Dimitri!) - Add missing include for [GCC 11](https://gcc.gnu.org/gcc-11/porting_to.html#header-dep-changes) ([#68](https://github.com/asmaloney/libE57Format/pull/68)) (Thanks bartoszek!) +**Note:** The next release will be 3.0 and will require a [C++14](https://en.cppreference.com/w/cpp/14) compiler. + ## [2.2.0](https://github.com/asmaloney/libE57Format/releases/tag/v2.2.0) - 2021-04-01 ### Added @@ -35,7 +182,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Other - Removed all internal usage of dynamic_cast<>. ([#39](https://github.com/asmaloney/libE57Format/pull/39)) (Thanks Jiri!) -- Split classes out from E57FormatImpl.[h,cpp] intot their own files. +- Split classes out from E57FormatImpl.[h,cpp] into their own files. ## [2.1.0](https://github.com/asmaloney/libE57Format/releases/tag/v2.1) - 2020-04-01 diff --git a/src/3rdParty/libE57Format/CMakeLists.txt b/src/3rdParty/libE57Format/CMakeLists.txt index e5b17813ac752..41c41f71dfa2f 100644 --- a/src/3rdParty/libE57Format/CMakeLists.txt +++ b/src/3rdParty/libE57Format/CMakeLists.txt @@ -3,8 +3,8 @@ # # Use git blame to see all the changes and who has contributed. # +# Copyright 2018-2023 Andy Maloney # Original work Copyright 2010-2012 Roland Schwarz, Riegl LMS GmbH -# Modified work Copyright 2018-2020 Andy Maloney # # Permission is hereby granted, free of charge, to any person or organization # obtaining a copy of the software and accompanying documentation covered by @@ -28,10 +28,12 @@ # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -cmake_minimum_required( VERSION 3.10.0 ) +cmake_minimum_required( VERSION 3.15 ) # Set a private module find path -set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules/" ) +set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/" ) + +message( STATUS "Using CMake ${CMAKE_VERSION}" ) project( E57Format DESCRIPTION @@ -39,9 +41,13 @@ project( E57Format LANGUAGES CXX VERSION - 2.2.1 + 3.0.2 ) +string( TOUPPER ${PROJECT_NAME} PROJECT_NAME_UPPERCASE ) + +# Creates a build tag which is used in the REVISION_ID +# e.g. "x86_64-darwin-AppleClang140" include( Tags ) # Check if we are building ourself or being included and use this to set some defaults @@ -77,90 +83,107 @@ if( BUILD_SHARED_LIBS ) endif() ######################################################################################### - -# Various levels of cross checking and verification in the code. +# Cross checking and runtime verification in the code. # The extra code does not change the file contents. -# Recommend that E57_DEBUG remain defined even for production versions. +# E57_VALIDATION_LEVEL=0 off +# E57_VALIDATION_LEVEL=1 basic +# E57_VALIDATION_LEVEL=2 deep (implies basic) - checks at the packet level, so it will be slower +set( E57_VALIDATION_LEVEL "1" CACHE STRING "Runtime validation level (0 = OFF, 1 = basic, 2 = deep)" ) -option( E57_DEBUG "Compile library with minimal debug checking" ON ) -option( E57_MAX_DEBUG "Compile library with maximum debug checking" OFF ) +# Output detailed logging while processing. +option( E57_VERBOSE "Compile library with verbose logging" OFF ) -# Various levels of printing to the console of what is going on in the code. -# Optional - -option( E57_VERBOSE "Compile library with verbose logging" OFF ) -option( E57_MAX_VERBOSE "Compile library with maximum verbose logging" OFF ) +# Enable/disable code which dumps detailed node info to std::ostream. (See NodeImpl::dump()) +# Instead of always including this code, it is an option for backwards compatibility. +# The only real reason to turn this off would be for slightly smaller binaries. +option( E57_ENABLE_DIAGNOSTIC_OUTPUT "Include code for diagnostic output using dump() on nodes" ON ) # Enable writing packets that are correct but will stress the reader. - option( E57_WRITE_CRAZY_PACKET_MODE "Compile library to enable reader-stressing packets" OFF ) -######################################################################################### +# Other compile options -set( revision_id "${PROJECT_NAME}-${PROJECT_VERSION}-${${PROJECT_NAME}_BUILD_TAG}" ) -message( STATUS "[E57] Revison ID: ${revision_id}" ) +# Link-time optiomization +# CMake forces "thin" LTO (see https://gitlab.kitware.com/cmake/cmake/-/issues/23136) +# which is a problem if compiling statically for distribution (e.g. in a package manager). +# Generally you will only want to turn this off for distributing static release builds. +option( E57_RELEASE_LTO "Compile release library with link-time optimization" ON ) -# Need to explicitly set the source files to add_library() -if(${CMAKE_VERSION} VERSION_LESS "3.11.0") - file(GLOB E57Format_SOURCES src/[^.]*.cpp) -endif() +######################################################################################### + +set( REVISION_ID "${PROJECT_NAME}-${PROJECT_VERSION}-${${PROJECT_NAME}_BUILD_TAG}" ) +message( STATUS "[${PROJECT_NAME}] Revision ID: ${REVISION_ID}" ) # Target if ( E57_BUILD_SHARED ) - message( STATUS "[E57] Building shared library" ) - add_library( E57Format SHARED ${E57Format_SOURCES}) + message( STATUS "[${PROJECT_NAME}] Building shared library" ) + add_library( E57Format SHARED ) else() - message( STATUS "[E57] Building static library" ) - add_library( E57Format STATIC ${E57Format_SOURCES}) + message( STATUS "[${PROJECT_NAME}] Building static library" ) + add_library( E57Format STATIC ) endif() include( E57ExportHeader ) +include( GitUpdate ) # Main sources and includes add_subdirectory( extern/CRCpp ) add_subdirectory( include ) add_subdirectory( src ) -include( ClangFormat ) - # Target properties set_target_properties( E57Format PROPERTIES - CXX_STANDARD 11 - CXX_STANDARD_REQUIRED YES - CXX_EXTENSIONS NO - DEBUG_POSTFIX "-d" + CXX_EXTENSIONS NO + EXPORT_COMPILE_COMMANDS ON POSITION_INDEPENDENT_CODE ON + INTERPROCEDURAL_OPTIMIZATION ${E57_RELEASE_LTO} + INTERPROCEDURAL_OPTIMIZATION_DEBUG OFF ) -# Target definitions -target_compile_definitions( E57Format +if( NOT DEFINED CMAKE_DEBUG_POSTFIX ) + set_target_properties( E57Format + PROPERTIES + DEBUG_POSTFIX "-d" + ) +endif() + +target_compile_features( ${PROJECT_NAME} PRIVATE - CRCPP_USE_CPP11 - CRCPP_BRANCHLESS - REVISION_ID="${revision_id}" + cxx_std_14 ) -if ( E57_DEBUG ) - target_compile_definitions( E57Format PRIVATE E57_DEBUG ) -endif() +# Warnings +include( CompilerWarnings ) -if ( E57_MAX_DEBUG ) - target_compile_definitions( E57Format PRIVATE E57_MAX_DEBUG ) +# Treat warnings as errors if we are building ourself. +if ( E57_BUILDING_SELF ) + unset( ${PROJECT_NAME_UPPERCASE}_WARNING_AS_ERROR CACHE ) + set_warning_as_error() endif() -if ( E57_VERBOSE ) - target_compile_definitions( E57Format PRIVATE E57_VERBOSE ) -endif() +# Check our validation level +string( STRIP "${E57_VALIDATION_LEVEL}" E57_VALIDATION_LEVEL ) +if ( NOT E57_VALIDATION_LEVEL MATCHES "^[0-2]$" ) + message( FATAL_ERROR "[${PROJECT_NAME}] E57_VALIDATION_LEVEL should be 0-2: '${E57_VALIDATION_LEVEL}'" ) +else() + message( STATUS "[${PROJECT_NAME}] Setting validation level to ${E57_VALIDATION_LEVEL}" ) +endif () -if ( E57_MAX_VERBOSE ) - target_compile_definitions( E57Format PRIVATE E57_MAX_VERBOSE ) -endif() +# Target definitions +target_compile_definitions( E57Format + PRIVATE + REVISION_ID="${REVISION_ID}" + E57_VALIDATION_LEVEL=${E57_VALIDATION_LEVEL} + $<$:E57_ENABLE_DIAGNOSTIC_OUTPUT> + $<$:E57_VERBOSE> + $<$:E57_WRITE_CRAZY_PACKET_MODE> +) -if ( E57_WRITE_CRAZY_PACKET_MODE ) - target_compile_definitions( E57Format PRIVATE E57_WRITE_CRAZY_PACKET_MODE ) -endif() +# sanitizers +include( Sanitizers ) +# xerces if ( WIN32 ) option( USING_STATIC_XERCES "Turn on if you are linking with Xerces as a static lib" OFF ) if ( USING_STATIC_XERCES ) @@ -180,21 +203,40 @@ install( E57Format EXPORT E57Format-export - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) +# ccache +# Turns on ccache if found +include( ccache ) + +# Formatting +include( ClangFormat ) + +# Testing +option( E57_BUILD_TEST + "Build tests" + ${E57_BUILDING_SELF} +) + +if ( E57_BUILD_TEST ) + message( STATUS "[${PROJECT_NAME}] Testing enabled" ) + + enable_testing() + + add_subdirectory( test ) +endif() + # CMake package files -#install( -# EXPORT -# E57Format-export -# DESTINATION lib/cmake/E57Format -#) - -#install( -# FILES -# ${CMAKE_CURRENT_SOURCE_DIR}/cmake/e57format-config.cmake -# DESTINATION -# lib/cmake/E57Format -#) +install( + EXPORT + E57Format-export + DESTINATION + lib/cmake/E57Format +) + +install( + FILES + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/e57format-config.cmake + DESTINATION + lib/cmake/E57Format +) diff --git a/src/3rdParty/libE57Format/CONTRIBUTING.md b/src/3rdParty/libE57Format/CONTRIBUTING.md index d84c3e7e6862d..73d9ab3545fc2 100644 --- a/src/3rdParty/libE57Format/CONTRIBUTING.md +++ b/src/3rdParty/libE57Format/CONTRIBUTING.md @@ -1,21 +1,37 @@ # How To Contribute -## Code Changes +These are some of the things you can do to contribute to the project: + +## ✍ Write About The Project + +If you find the project useful, spread the word! Articles, mastodon posts, tweets, blog posts, instagram photos - whatever you're into. Please include a referral back to the repository page: https://github.com/asmaloney/libE57Format + +## ⭐️ Add a Star + +If you found this project useful, please consider starring it! It helps me gauge how useful this project is. + +## ☝ Raise Issues + +If you run into something which doesn't work as expected, raising [an issue](https://github.com/asmaloney/libE57Format/issues) with all the relevant information to reproduce it would be helpful. + +## 🐞 Bug Fixes & πŸ§ͺ New Things I am happy to review any [pull requests](https://github.com/asmaloney/libE57Format/pulls). Please keep them as short as possible. Each pull request should be atomic and only address one issue. This helps with the review process. +Note that I will not accept everything, but I welcome discussion. If you are proposing a big change, please raise it as [an issue](https://github.com/asmaloney/libE57Format/issues) first for discussion. + ### Formatting -This project uses [clang-format](https://clang.llvm.org/docs/ClangFormat.html) to format the code. There is a cmake target (_format_) - which runs _clang-format_ on the source files. After changes have been made, and before you submit your pull request, please run the following: +This project uses [clang-format](https://clang.llvm.org/docs/ClangFormat.html) to format the code. There is a cmake target (_e57-clang-format_) - which runs _clang-format_ on the source files. After changes have been made, and before you submit your pull request, please run the following: ```sh -cmake --build . --target format +cmake --build . --target e57-clang-format ``` -## Documentation +## πŸ“– Documentation The [documentation](https://github.com/asmaloney/libE57Format) is a bit old and could use some lovin'. You can submit changes over in the [libE57Format-docs](https://github.com/asmaloney/libE57Format-docs) repository. -## Financial +## πŸ’° Financial -If you would like to support the project financially, you can use the **Sponsor** button at the top of the [libE57Format](https://github.com/asmaloney/libE57Format) repository page. +Given that I'm an independent developer without funding, financial support is always appreciated. If you would like to support the project financially (especially if you sell a product which uses this library), you can use the [sponsors page](https://github.com/sponsors/asmaloney) for one-off or recurring support. Thank you! diff --git a/src/3rdParty/libE57Format/README.md b/src/3rdParty/libE57Format/README.md index 66a6876b36786..6838597ccab78 100644 --- a/src/3rdParty/libE57Format/README.md +++ b/src/3rdParty/libE57Format/README.md @@ -1,40 +1,149 @@ # libE57Format -[![Build Status](https://travis-ci.org/asmaloney/libE57Format.svg?branch=master)](https://travis-ci.org/asmaloney/libE57Format) +[![GitHub release (latest by date)](https://img.shields.io/github/v/release/asmaloney/libE57Format)](https://github.com/asmaloney/libE57Format/releases/latest) [![Docs](https://img.shields.io/badge/docs-online-orange)](https://asmaloney.github.io/libE57Format-docs/) [![GitHub](https://img.shields.io/github/license/asmaloney/libE57Format)](LICENSE) ![Build](https://github.com/asmaloney/libE57Format/actions/workflows/build.yml/badge.svg) -A library to provide read & write support for the E57 file format. +libE57Format is a C++ library which provides read & write support for the ASTM-standard [E57 file format](https://www.astm.org/e2807-11r19e01.html) on Linux, macOS, and Windows. E57 files store 3D point cloud data (produced by 3D imaging systems such as laser scanners), attributes associated with 3D point data (color & intensity), and 2D images (photos taken using a 3D imaging system). -This is a fork of [E57RefImpl](https://sourceforge.net/projects/e57-3d-imgfmt/) v1.1.332. The original source is from [E57RefImpl 1.1.332](https://sourceforge.net/projects/e57-3d-imgfmt/files/E57Refimpl-src/) and then everything was stripped out except the main implementation for reading and writing E57. +## Documentation -This version also removes the dependency on [Boost](http://www.boost.org/) and requires C++11. +The doxygen-generated documentation may be [found here](https://asmaloney.github.io/libE57Format-docs/). These docs are generated and saved in the [libE57Format-docs](https://github.com/asmaloney/libE57Format-docs) repo. -Many, many other changes were made prior to the first release of this fork. See the [CHANGELOG](CHANGELOG.md) and git history for details. +## Dependencies/Requirements -## Documentation +Tools: -The doxygen-generated documentation may be [found here](https://asmaloney.github.io/libE57Format-docs/). These docs are generated and saved in the [libE57Format-docs](https://github.com/asmaloney/libE57Format-docs) repo. +- a [C++14](https://en.cppreference.com/w/cpp/14) compatible compiler +- [CMake](https://cmake.org/) >= 3.15 +- [clang-format](https://clang.llvm.org/docs/ClangFormat.html) for code formatting +- (_optional_) [ccache](https://ccache.dev/) to speed up rebuilds + +Libraries: + +- [Xerces-C++](https://xerces.apache.org/xerces-c/) (for parsing XML) + +### Installing Dependencies On Linux (Ubuntu) + +```sh +$ sudo apt install libxerces-c-dev clang-format +``` + +### Installing Dependencies On macOS (homebrew) + +```sh +$ brew install ccache clang-format xerces-c +``` -## Contributing +## Build, Install, & Test -Please see [CONTRIBUTING](CONTRIBUTING.md). +Here's how you build & install a release version with the defaults: -## Why Fork? +``` +$ cmake -B E57-build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=E57-install libE57Format +$ cmake --build E57-build --parallel +$ cmake --install E57-build +``` -The E57RefImpl code hasn't been touched in years and I wanted to make changes to compile this library with macOS. Forking it gives me a bit more freedom to update the code and make changes as required. +If CMake can't find the xerces-c library, you can set [CMAKE_PREFIX_PATH](https://cmake.org/cmake/help/latest/variable/CMAKE_PREFIX_PATH.html) to point at it. -I changed the name of the project so that it is not confused with the **E57RefImpl** project. +``` +$ cmake -B E57-build \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX=E57-install \ + -DCMAKE_PREFIX_PATH=/path/to/xerces-c \ + libE57Format +``` -I have also changed the main include file's name from `E57Foundation.h` to `E57Format.h` to make sure there is no inclusion confusion. +Once the library is built, you can run the tests like this: -Versions of **libE57Format** started at 2.0. +``` +$ cd E57-build +$ ./test/testE57 +[==========] Running 36 tests from 8 test suites. +[----------] Global test environment set-up. +[----------] 1 test from TestData +[ RUN ] TestData.RepoExists +... +``` + +See [test/README](test/README.md) for details about testing and the test data. + +## 🍴 Fork + +This is a fork of [E57RefImpl](https://sourceforge.net/projects/e57-3d-imgfmt/). The original source is from [E57RefImpl 1.1.332](https://sourceforge.net/projects/e57-3d-imgfmt/files/E57Refimpl-src/). + +The original code had not been touched in years and I wanted to make changes to compile it on macOS. Forking it gave me a bit more freedom to update the code and make changes as required. Everything was stripped out except the main implementation for reading & writing E57 files. + +Notes: + +- I changed the name of the project so that it is not confused with the **E57RefImpl** project. +- I changed the main include file's name from `E57Foundation.h` to `E57Format.h` to make sure there is no inclusion confusion. +- Versions of **libE57Format** started at 2.0. +- I made changes for it to compile and run on macOS. +- It no longer depends on [Boost](http://www.boost.org/). +- It now requires [C++14](https://en.cppreference.com/w/cpp/14). (Version 2.x required [C++11](https://en.cppreference.com/w/cpp/11).) + +Many, many other changes were made prior to the first release of this fork. See the [CHANGELOG](CHANGELOG.md) and git history for details. ### E57Simple API -Since the original fork, [Jiri HΓΆrner](https://github.com/ptc-jhoerner) has added the E57Simple API from the old reference implementation and updated it. +[Jiri HΓΆrner](https://github.com/ptc-jhoerner) added the E57Simple API from the old reference implementation and updated it. + +This _Simple API_ has evolved since this original port to fix some problems and to make it more foolproof & easier to use. Please see the [CHANGELOG](CHANGELOG.md) for version 3. ### Tools -[Ryan Baumann](https://github.com/ryanfb) has updated the `e57unpack` and `e57validate` tools to work with **libE57Format**. You can find them in the [e57tools](https://github.com/ryanfb/e57tools) repo. +[Ryan Baumann](https://github.com/ryanfb) updated the `e57unpack` and `e57validate` tools to work with **libE57Format**. You can find them in the [e57tools](https://github.com/ryanfb/e57tools) repo. + +## Projects Using libE57Format + +- [CloudCompare](https://github.com/CloudCompare/CloudCompare) +- [MeshLab](https://github.com/cnr-isti-vclab/meshlab) +- [pye57](https://github.com/davidcaron/pye57) + +These projects use hard forks of libE57Format: + +- [FreeCAD](https://github.com/FreeCAD/FreeCAD) +- [PDAL](https://github.com/PDAL/PDAL) + +There are also some commercial products using libE57Format. If any of them would like to sponsor the project and be listed here, please contact Andy (asmaloney). + +## How To Contribute + +These are some of the things you can do to contribute to the project: + +### ✍ Write About The Project + +If you find the project useful, spread the word! Articles, mastodon posts, tweets, blog posts, instagram photos - whatever you're into. + +### ⭐️ Add a Star + +If you found this project useful, please consider starring it! It helps me gauge how useful this project is. + +### ☝ Raise Issues + +If you run into something which doesn't work as expected, raising [an issue](https://github.com/asmaloney/libE57Format/issues) with all the relevant information to reproduce it would be helpful. + +### 🐞 Bug Fixes & πŸ§ͺ New Things + +I am happy to review any [pull requests](https://github.com/asmaloney/libE57Format/pulls). Please keep them as short as possible. Each pull request should be atomic and only address one issue. This helps with the review process. + +Note that I will not accept everything, but I welcome discussion. If you are proposing a big change, please raise it as [an issue](https://github.com/asmaloney/libE57Format/issues) first for discussion. + +#### Formatting + +This project uses [clang-format](https://clang.llvm.org/docs/ClangFormat.html) to format the code. There is a cmake target (_e57-clang-format_) - which runs _clang-format_ on the source files. After changes have been made, and before you submit your pull request, please run the following: + +```sh +cmake --build . --target e57-clang-format +``` + +### πŸ“– Documentation + +The [documentation](https://github.com/asmaloney/libE57Format) is a bit old and could use some lovin'. You can submit changes over in the [libE57Format-docs](https://github.com/asmaloney/libE57Format-docs) repository. + +### πŸ’° Financial + +Given that I'm an independent developer without funding, financial support is always appreciated. If you would like to support the project financially (especially if you sell a product which uses this library), you can use the [sponsors page](https://github.com/sponsors/asmaloney) for one-off or recurring support. Thank you! ## License @@ -44,7 +153,7 @@ Individual source files may contain the following tag instead of the full licens SPDX-License-Identifier: BSL-1.0 -Some CMake files are licensed under the **MIT** license - see the [LICENSE-MIT](LICENSE-MIT.txt) file for details. +Some files are licensed under the **MIT** license - see the [LICENSE-MIT](LICENSE-MIT.txt) file for details. These files contain the following tag instead of the full license text: diff --git a/src/3rdParty/libE57Format/cmake/ClangFormat.cmake b/src/3rdParty/libE57Format/cmake/ClangFormat.cmake new file mode 100644 index 0000000000000..e1ace358909ed --- /dev/null +++ b/src/3rdParty/libE57Format/cmake/ClangFormat.cmake @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: MIT +# Copyright 2020 Andy Maloney + +find_program( E57_CLANG_FORMAT_PROGRAM NAMES clang-format ) + +if ( E57_CLANG_FORMAT_PROGRAM ) + message( STATUS "[${PROJECT_NAME}] Using clang-format: ${E57_CLANG_FORMAT_PROGRAM}" ) + + get_target_property( e57_sources ${PROJECT_NAME} SOURCES ) + + # Remove some files from the list + list( FILTER e57_sources EXCLUDE REGEX ".*/E57Export.h" ) + list( FILTER e57_sources EXCLUDE REGEX ".*/extern/.*" ) + + # Get list of test files. We cannot use get_target_property here + # since we will not have a target if E57_BUILD_TEST is off. + file( GLOB e57_test_sources + LIST_DIRECTORIES false + CONFIGURE_DEPENDS + ${PROJECT_SOURCE_DIR}/test/include/*.h + ${PROJECT_SOURCE_DIR}/test/src/*.cpp + ) + + list( APPEND e57_sources ${e57_test_sources} ) + + add_custom_target( e57-clang-format + COMMAND ${E57_CLANG_FORMAT_PROGRAM} --style=file -i ${e57_sources} + COMMENT "Running clang-format..." + COMMAND_EXPAND_LISTS + VERBATIM + ) +endif() diff --git a/src/3rdParty/libE57Format/cmake/CompilerWarnings.cmake b/src/3rdParty/libE57Format/cmake/CompilerWarnings.cmake new file mode 100644 index 0000000000000..9a9e5076dc84c --- /dev/null +++ b/src/3rdParty/libE57Format/cmake/CompilerWarnings.cmake @@ -0,0 +1,112 @@ +# SPDX-License-Identifier: MIT +# Copyright 2022 Andy Maloney + +string( TOUPPER ${PROJECT_NAME} PROJECT_NAME_UPPERCASE ) + +if ( NOT MSVC ) + option( ${PROJECT_NAME_UPPERCASE}_WARN_EVERYTHING "Turn on all warnings (not recommended - used for lib development)" OFF ) +endif() + +option( ${PROJECT_NAME_UPPERCASE}_WARNING_AS_ERROR "Treat warnings as errors" OFF ) + +# Set some helper variables for readability +set( compiler_is_clang "$,$>" ) +set( compiler_is_gnu "$" ) +set( compiler_is_msvc "$" ) + +target_compile_options( ${PROJECT_NAME} + PRIVATE + # MSVC only + $<${compiler_is_msvc}: + /W4 + /w14263 # 'function': member function does not override any base class virtual member function + /w14296 # 'operator': expression is always 'boolean_value' + /w14311 # 'variable': pointer truncation from 'type1' to 'type2' + /w14545 # expression before comma evaluates to a function which is missing an argument list + /w14546 # function call before comma missing argument list + /w14547 # 'operator': operator before comma has no effect; expected operator with side-effect + /w14549 # 'operator': operator before comma has no effect; did you intend 'operator'? + /w14619 # pragma warning: there is no warning number 'number' + /w14640 # thread un-safe static member initialization + /w14905 # wide string literal cast to 'LPSTR' + /w14906 # string literal cast to 'LPWSTR' + + /wd4251 # 'type' : class 'type1' needs to have dll-interface to be used by clients of class 'type2' + > + # Clang and GNU common options + $<$: + -Wall + -Wcast-align + -Wextra + -Wformat=2 + -Wnon-virtual-dtor + -Wnull-dereference + -Woverloaded-virtual + -Wpedantic + -Wshadow + -Wunused + > + # Clang only + $<${compiler_is_clang}: + -Wdocumentation + -Wno-documentation-deprecated-sync # because enumerator [[deprecated]] attribute is C++17 + > + # GNU only + $<${compiler_is_gnu}: + -Wduplicated-branches + -Wduplicated-cond + -Wlogical-op + > +) + +# Turn on (almost) all warnings on Clang, Apple Clang, and GNU. +# Useful for internal development, but too noisy for general development. +function( set_warn_everything ) + message( STATUS "[${PROJECT_NAME}] Turning on (almost) all warnings") + + target_compile_options( ${PROJECT_NAME} + PRIVATE + # Clang and GNU + $<$: + -Weverything + -Wno-c++98-compat + -Wno-c++98-compat-pedantic + -Wno-padded + > + # Clang only + $<${compiler_is_clang}: + -Wno-documentation-deprecated-sync # because enumerator [[deprecated]] attribute is C++17 + > + ) +endfunction() + +if ( NOT MSVC AND ${PROJECT_NAME_UPPERCASE}_WARN_EVERYTHING ) + set_warn_everything() +endif() + +# Treat warnings as errors +function( set_warning_as_error ) + message( STATUS "[${PROJECT_NAME}] Treating warnings as errors") + + if ( CMAKE_VERSION VERSION_GREATER_EQUAL "3.24" ) + set_target_properties( ${PROJECT_NAME} + PROPERTIES + COMPILE_WARNING_AS_ERROR ON + ) + else() + # This will do nothing on compilers other than MSVC, Clang, Apple Clang, and GNU compilers. + target_compile_options( ${PROJECT_NAME} + PRIVATE + $<${compiler_is_msvc}: + /WX + > + $<$: + -Werror + > + ) + endif() +endfunction() + +if ( ${PROJECT_NAME_UPPERCASE}_WARNING_AS_ERROR ) + set_warning_as_error() +endif() diff --git a/src/3rdParty/libE57Format/cmake/Modules/E57ExportHeader.cmake b/src/3rdParty/libE57Format/cmake/E57ExportHeader.cmake similarity index 88% rename from src/3rdParty/libE57Format/cmake/Modules/E57ExportHeader.cmake rename to src/3rdParty/libE57Format/cmake/E57ExportHeader.cmake index b9eaa6ca94f57..11521599ed5b7 100644 --- a/src/3rdParty/libE57Format/cmake/Modules/E57ExportHeader.cmake +++ b/src/3rdParty/libE57Format/cmake/E57ExportHeader.cmake @@ -5,7 +5,9 @@ include( GenerateExportHeader ) -set( comment "// NOTE: This is a generated file. Any changes will be overwritten." ) +set( comment "\r +// NOTE: This is a generated file. Any changes will be overwritten." +) generate_export_header( E57Format EXPORT_FILE_NAME E57Export.h diff --git a/src/3rdParty/libE57Format/cmake/GitUpdate.cmake b/src/3rdParty/libE57Format/cmake/GitUpdate.cmake new file mode 100644 index 0000000000000..178a571f7b9d8 --- /dev/null +++ b/src/3rdParty/libE57Format/cmake/GitUpdate.cmake @@ -0,0 +1,22 @@ +find_package( Git QUIET ) + +if ( GIT_FOUND AND EXISTS "${PROJECT_SOURCE_DIR}/.git" ) + # Update submodules as needed + option( E57_GIT_SUBMODULE_UPDATE "Check submodules and update during build" ON ) + + if ( E57_GIT_SUBMODULE_UPDATE ) + message( STATUS "Submodule update using git (${GIT_EXECUTABLE})" ) + message( STATUS "Submodule update directory: ${CMAKE_CURRENT_SOURCE_DIR}" ) + + execute_process( COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + RESULT_VARIABLE GIT_SUBMOD_RESULT + ERROR_VARIABLE GIT_SUBMOD_RESULT) + + if ( GIT_SUBMOD_RESULT EQUAL "0" ) + message( STATUS "Submodule update complete" ) + else() + message( FATAL_ERROR "Submodule update failed with ${GIT_SUBMOD_RESULT}, please checkout submodules" ) + endif() + endif() +endif() diff --git a/src/3rdParty/libE57Format/cmake/Modules/ClangFormat.cmake b/src/3rdParty/libE57Format/cmake/Modules/ClangFormat.cmake deleted file mode 100644 index 6e793ecf0baf2..0000000000000 --- a/src/3rdParty/libE57Format/cmake/Modules/ClangFormat.cmake +++ /dev/null @@ -1,19 +0,0 @@ -# SPDX-License-Identifier: MIT -# Copyright 2020 Andy Maloney - -find_program( E57_CLANG_FORMAT_EXE NAMES clang-format ) - -if ( E57_CLANG_FORMAT_EXE ) - get_target_property( e57_sources ${PROJECT_NAME} SOURCES ) - - # Remove some files from the list - list( FILTER e57_sources EXCLUDE REGEX ".*/E57Export.h" ) - list( FILTER e57_sources EXCLUDE REGEX ".*/extern/.*" ) - - add_custom_target( format - COMMAND clang-format --style=file -i ${e57_sources} - COMMENT "Running clang-format..." - COMMAND_EXPAND_LISTS - VERBATIM - ) -endif() diff --git a/src/3rdParty/libE57Format/cmake/Modules/Tags.cmake b/src/3rdParty/libE57Format/cmake/Modules/Tags.cmake deleted file mode 100644 index 421cc70b0ff5d..0000000000000 --- a/src/3rdParty/libE57Format/cmake/Modules/Tags.cmake +++ /dev/null @@ -1,41 +0,0 @@ -# This file defines the variables -# ${PROJECT_NAME}_BUILD_TAG - -# calculate the tag -set(T_ ${CMAKE_SYSTEM_PROCESSOR}) -if (CMAKE_CL_64) - set(T_ ${T_}_64) -endif (CMAKE_CL_64) -string(TOLOWER ${CMAKE_SYSTEM_NAME} T1_) -set(T_ ${T_}-${T1_}) -if (MSVC90) - set(T1_ "-vc90") -elseif (MSVC10) - set(T1_ "-vc100") -elseif (MSVC80) - set(T1_ "-vc80") -elseif (MSVC71) - set(T1_ "-vc711") -elseif (MSVC70) - set(T1_ "-vc7") -elseif (MINGW) - set(T1_ "-mgw") - exec_program(${CMAKE_CXX_COMPILER} - ARGS ${CMAKE_CXX_COMPILER_ARG1} -dumpversion - OUTPUT_VARIABLE T2_ - ) - string(REGEX REPLACE "([0-9])\\.([0-9])(\\.[0-9])?" "\\1\\2" T2_ ${T2_}) - set(T1_ ${T1_}${T2_}) -elseif (CMAKE_COMPILER_IS_GNUCXX) - set(T1_ "-gcc") - exec_program(${CMAKE_CXX_COMPILER} - ARGS ${CMAKE_CXX_COMPILER_ARG1} -dumpversion - OUTPUT_VARIABLE T2_ - ) - string(REGEX REPLACE "([0-9])\\.([0-9])(\\.[0-9])?" "\\1\\2" T2_ ${T2_}) - set(T1_ ${T1_}${T2_}) -else() - set(T1_) -endif() -set(T_ ${T_}${T1_}) -set(${PROJECT_NAME}_BUILD_TAG ${T_}) diff --git a/src/3rdParty/libE57Format/cmake/Sanitizers.cmake b/src/3rdParty/libE57Format/cmake/Sanitizers.cmake new file mode 100644 index 0000000000000..582260877187d --- /dev/null +++ b/src/3rdParty/libE57Format/cmake/Sanitizers.cmake @@ -0,0 +1,93 @@ +# SPDX-License-Identifier: MIT +# Copyright 2023 Andy Maloney + +# Note: In theory address sanitization should work on MSVC, but I could not get it working. +# If you know how to fix it, please submit a PR: +# https://github.com/asmaloney/libE57Format/pulls + +string( TOUPPER ${PROJECT_NAME} PROJECT_NAME_UPPERCASE ) + +set( compiler_is_clang "$,$>" ) +set( compiler_is_gnu "$" ) +set( compiler_is_msvc "$" ) +set( compiler_is_not_msvc "$" ) + +if ( NOT MSVC ) + option( ${PROJECT_NAME_UPPERCASE}_SANITIZE_ALL "Enable all sanitizers if available." OFF ) + option( ${PROJECT_NAME_UPPERCASE}_SANITIZE_ADDRESS "Enable address sanitizer (ASan) if available." OFF ) + option( ${PROJECT_NAME_UPPERCASE}_SANITIZE_UNDEFINED "Enable memory sanitizer (UBSan) if available." OFF ) +endif() + +function( enable_address_sanitizer target ) + message( STATUS "[${target}] Enabling address sanitizer (ASan)" ) + + target_compile_options( ${target} + PRIVATE + $<${compiler_is_not_msvc}: + -fno-omit-frame-pointer + -fsanitize=address + > + + $<${compiler_is_msvc}: + /fsanitize=address + /INCREMENTAL:NO + /Zi + > + ) + target_link_options( ${target} + PUBLIC + $<${compiler_is_not_msvc}: + -fno-omit-frame-pointer + -fsanitize=address + > + + $<${compiler_is_msvc}: + /DEBUG + /INCREMENTAL:NO + > + ) +endfunction() + +function( enable_undefined_sanitizer target ) + if ( MSVC ) + message( WARNING "[${target}] Undefined behaviour sanitizer (UBSan) not avaiable for MSVC" ) + return() + endif() + + message( STATUS "[${target}] Enabling undefined behaviour sanitizer (UBSan)" ) + + target_compile_options( ${target} + PRIVATE + -fsanitize=undefined + ) + target_link_options( ${target} + PUBLIC + -fsanitize=undefined + ) +endfunction() + +function( enable_all_sanitizers target ) + if ( MSVC ) + return() + endif() + + unset( ${PROJECT_NAME_UPPERCASE}_SANITIZE_ADDRESS CACHE ) + unset( ${PROJECT_NAME_UPPERCASE}_SANITIZE_UNDEFINED CACHE ) + + enable_address_sanitizer( ${target} ) + enable_undefined_sanitizer( ${target} ) +endfunction() + +if ( NOT MSVC ) + if ( ${PROJECT_NAME_UPPERCASE}_SANITIZE_ALL ) + enable_all_sanitizers( ${PROJECT_NAME} ) + else() + if ( ${PROJECT_NAME_UPPERCASE}_SANITIZE_ADDRESS ) + enable_address_sanitizer( ${PROJECT_NAME} ) + endif() + + if ( ${PROJECT_NAME_UPPERCASE}_SANITIZE_UNDEFINED ) + enable_undefined_sanitizer( ${PROJECT_NAME} ) + endif() + endif() +endif() diff --git a/src/3rdParty/libE57Format/cmake/Tags.cmake b/src/3rdParty/libE57Format/cmake/Tags.cmake new file mode 100644 index 0000000000000..9ad18921f95f9 --- /dev/null +++ b/src/3rdParty/libE57Format/cmake/Tags.cmake @@ -0,0 +1,38 @@ +# This file defines the variables +# ${PROJECT_NAME}_BUILD_TAG + +set( T_ ${CMAKE_SYSTEM_PROCESSOR} ) + +string( TOLOWER ${CMAKE_SYSTEM_NAME} T1_ ) + +function( add_compiler_version ) + exec_program( ${CMAKE_CXX_COMPILER} + ARGS ${CMAKE_CXX_COMPILER_ARG1} -dumpversion + OUTPUT_VARIABLE T2_ + ) + string( REGEX REPLACE "([0-9])\\.([0-9])(\\.[0-9])?" "\\1\\2" T2_ ${T2_} ) + set( T1_ ${T1_}${T2_} PARENT_SCOPE ) +endfunction() + +# default to just the CMake compiler ID +set( T1_ ${CMAKE_CXX_COMPILER_ID} ) + +# special cases to add versions and other info +if ( MSVC ) + if ( CMAKE_CL_64 ) + set( T_ ${T_}_64 ) + endif() + + set( T1_ "vc${MSVC_VERSION}" ) +elseif ( MINGW ) + set( T1_ "MinGW" ) + add_compiler_version() +elseif ( CMAKE_CXX_COMPILER_ID STREQUAL "GNU" ) + set( T1_ "gcc" ) + add_compiler_version() +elseif ( CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compiler_version() +endif() + +set( T_ ${T_}-${T1_} ) +set( ${PROJECT_NAME}_BUILD_TAG ${T_} ) diff --git a/src/3rdParty/libE57Format/cmake/ccache.cmake b/src/3rdParty/libE57Format/cmake/ccache.cmake new file mode 100644 index 0000000000000..1e34965b2e2e8 --- /dev/null +++ b/src/3rdParty/libE57Format/cmake/ccache.cmake @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: MIT +# Copyright 2022 Andy Maloney + +# See: https://crascit.com/2016/04/09/using-ccache-with-cmake/ +find_program( CCACHE_PROGRAM ccache ) + +if ( CCACHE_PROGRAM ) + message( STATUS "[${PROJECT_NAME}] Using ccache: ${CCACHE_PROGRAM}" ) + + set_target_properties( ${PROJECT_NAME} + PROPERTIES + CXX_COMPILER_LAUNCHER "${CCACHE_PROGRAM}" + C_COMPILER_LAUNCHER "${CCACHE_PROGRAM}" + ) +endif() diff --git a/src/3rdParty/libE57Format/extern/CRCpp/CMakeLists.txt b/src/3rdParty/libE57Format/extern/CRCpp/CMakeLists.txt index a96a4e1cda966..dd03e5509c35e 100644 --- a/src/3rdParty/libE57Format/extern/CRCpp/CMakeLists.txt +++ b/src/3rdParty/libE57Format/extern/CRCpp/CMakeLists.txt @@ -3,12 +3,18 @@ # CRCpp from here: https://github.com/d-bahr/CRCpp +target_compile_definitions( ${PROJECT_NAME} + PRIVATE + CRCPP_USE_CPP11 + CRCPP_BRANCHLESS + ) + target_sources( ${PROJECT_NAME} PRIVATE - ${CMAKE_CURRENT_LIST_DIR}/inc/CRC.h + inc/CRC.h ) target_include_directories( ${PROJECT_NAME} PRIVATE - ${CMAKE_CURRENT_LIST_DIR}/inc + inc ) diff --git a/src/3rdParty/libE57Format/extern/CRCpp/LICENSE b/src/3rdParty/libE57Format/extern/CRCpp/LICENSE index 961d67f5766d0..106f0bc528403 100644 --- a/src/3rdParty/libE57Format/extern/CRCpp/LICENSE +++ b/src/3rdParty/libE57Format/extern/CRCpp/LICENSE @@ -1,5 +1,5 @@ CRC++ -Copyright (c) 2016, Daniel Bahr +Copyright (c) 2022, Daniel Bahr All rights reserved. Redistribution and use in source and binary forms, with or without diff --git a/src/3rdParty/libE57Format/extern/CRCpp/README.md b/src/3rdParty/libE57Format/extern/CRCpp/README.md index 6cde496e17259..0e3be149bb9e2 100644 --- a/src/3rdParty/libE57Format/extern/CRCpp/README.md +++ b/src/3rdParty/libE57Format/extern/CRCpp/README.md @@ -82,7 +82,24 @@ int main(int argc, char ** argv) This will return the same CRC as the first example. -Both of the above examples compute a CRC bit-by-bit. However, CRC++ also supports lookup tables, as the following example demonstrates: +If you need to compute a CRC on an input that is not a multiple of `CHAR_BIT` (usually 8 bits), use the `CalculateBits()` function instead: + +```cpp +int main(int argc, char ** argv) +{ + const unsigned char data[] = { 0x98, 0x76, 0x54, 0x32, 0x10 }; + + // Second argument is the number of bits. The input data must + // be a whole number of bytes. Pad any used bits with zeros. + std::uint32_t crc = CRC::CalculateBits(data, 37, CRC::CRC_32()); + + std::cout << std::hex << crc; + + return 0; +} +``` + +The above examples compute a CRC bit-by-bit. However, CRC++ also supports lookup tables, as the following example demonstrates: ```cpp int main(int argc, char ** argv) @@ -149,6 +166,56 @@ Define to enables C++11 features (move semantics, constexpr, static_assert, etc. * `#define CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS` Define to include definitions for little-used CRCs. Not defined by default. +### Build + +CRC does not require a build for basic usage; simply include the header file in your project. + +Unit tests and documentation can be built manually with the project files provided or automatically with CMake. + +To build documentation manually: +```bash +cd doxygen +doxygen Doxyfile.dox +``` + +To build unit tests manually via Make: +```bash +# Build +cd test/prj/gcc +make [debug|release] +# Run unit tests +bin/unittest +``` + +Project files and solutions for Visual Studio 2015, 2017 and 2022 are provided in `test/prj`. Simply open the solution file and run the project; no additional configuration should be necessary. + +CMake can also be used to build the documentation and unit tests. An out-of-source build is recommended. In this example, we will do an out-of-source build in the `build` directory: +```bash +mkdir -p build +cd build +cmake .. [-DBUILD_DOC=ON] +# Build and run unit tests +make tests +# Build documentation +make doxygen +# Install header file +sudo make install +``` + +Unit tests are built by default. Enable the `BUILD_DOC` CMake flag to also build documentation (requires [Doxygen](https://www.doxygen.nl/index.html)). + +### Documentation + +https://d-bahr.github.io/CRCpp/ + ### License CRC++ is free to use and provided under a BSD license. + +### References + +Catalog of CRCs: https://reveng.sourceforge.io/crc-catalogue/ + +5G-NR Specification 3GPP TS 38.212: https://www.etsi.org/deliver/etsi_ts/138200_138299/138212/15.03.00_60/ts_138212v150300p.pdf + +USB 2.0 Specification: https://www.usb.org/document-library/usb-20-specification diff --git a/src/3rdParty/libE57Format/extern/CRCpp/inc/CRC.h b/src/3rdParty/libE57Format/extern/CRCpp/inc/CRC.h index 1c41b295564bd..ce2878069d341 100644 --- a/src/3rdParty/libE57Format/extern/CRCpp/inc/CRC.h +++ b/src/3rdParty/libE57Format/extern/CRCpp/inc/CRC.h @@ -1,11 +1,11 @@ /** @file CRC.h @author Daniel Bahr - @version 0.2.0.6 + @version 1.2.0.0 @copyright @parblock CRC++ - Copyright (c) 2016, Daniel Bahr + Copyright (c) 2022, Daniel Bahr All rights reserved. Redistribution and use in source and binary forms, with or without @@ -52,7 +52,7 @@ multiplication in the bit-by-bit calculation instead of a small conditional. The branchless implementation may be faster on processor architectures which support single-instruction integer multiplication. #define CRCPP_USE_CPP11 - Define to enables C++11 features (move semantics, constexpr, static_assert, etc.). - #define CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS - Define to include definitions for little-used CRCs. + #define CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS - Define to include definitions for little-used CRCs. */ #ifndef CRCPP_CRC_H_ @@ -202,6 +202,18 @@ class CRC template static CRCType Calculate(const void * data, crcpp_size size, const Table & lookupTable, CRCType crc); + template + static CRCType CalculateBits(const void * data, crcpp_size size, const Parameters & parameters); + + template + static CRCType CalculateBits(const void * data, crcpp_size size, const Parameters & parameters, CRCType crc); + + template + static CRCType CalculateBits(const void * data, crcpp_size size, const Table & lookupTable); + + template + static CRCType CalculateBits(const void * data, crcpp_size size, const Table & lookupTable, CRCType crc); + // Common CRCs up to 64 bits. // Note: Check values are the computed CRCs when given an ASCII input of "123456789" (without null terminator) #ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS @@ -212,6 +224,7 @@ class CRC static const Parameters< crcpp_uint8, 6> & CRC_6_CDMA2000A(); static const Parameters< crcpp_uint8, 6> & CRC_6_CDMA2000B(); static const Parameters< crcpp_uint8, 6> & CRC_6_ITU(); + static const Parameters< crcpp_uint8, 6> & CRC_6_NR(); static const Parameters< crcpp_uint8, 7> & CRC_7(); #endif static const Parameters< crcpp_uint8, 8> & CRC_8(); @@ -219,9 +232,11 @@ class CRC static const Parameters< crcpp_uint8, 8> & CRC_8_EBU(); static const Parameters< crcpp_uint8, 8> & CRC_8_MAXIM(); static const Parameters< crcpp_uint8, 8> & CRC_8_WCDMA(); + static const Parameters< crcpp_uint8, 8> & CRC_8_LTE(); static const Parameters & CRC_10(); static const Parameters & CRC_10_CDMA2000(); static const Parameters & CRC_11(); + static const Parameters & CRC_11_NR(); static const Parameters & CRC_12_CDMA2000(); static const Parameters & CRC_12_DECT(); static const Parameters & CRC_12_UMTS(); @@ -232,8 +247,10 @@ class CRC static const Parameters & CRC_16_ARC(); static const Parameters & CRC_16_BUYPASS(); static const Parameters & CRC_16_CCITTFALSE(); + static const Parameters & CRC_16_MCRF4XX(); #ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS static const Parameters & CRC_16_CDMA2000(); + static const Parameters & CRC_16_CMS(); static const Parameters & CRC_16_DECTR(); static const Parameters & CRC_16_DECTX(); static const Parameters & CRC_16_DNP(); @@ -254,6 +271,9 @@ class CRC static const Parameters & CRC_24(); static const Parameters & CRC_24_FLEXRAYA(); static const Parameters & CRC_24_FLEXRAYB(); + static const Parameters & CRC_24_LTEA(); + static const Parameters & CRC_24_LTEB(); + static const Parameters & CRC_24_NRC(); static const Parameters & CRC_30(); #endif static const Parameters & CRC_32(); @@ -299,8 +319,8 @@ class CRC template static CRCType CalculateRemainder(const void * data, crcpp_size size, const Table & lookupTable, CRCType remainder); - template - static crcpp_constexpr IntegerType BoundedConstexprValue(IntegerType x); + template + static CRCType CalculateRemainderBits(unsigned char byte, crcpp_size numBits, const Parameters & parameters, CRCType remainder); }; /** @@ -320,13 +340,13 @@ inline CRC::Table CRC::Parameters::MakeTab /** @brief Constructs a CRC table from a set of CRC parameters - @param[in] parameters CRC parameters + @param[in] params CRC parameters @tparam CRCType Integer type for storing the CRC result @tparam CRCWidth Number of bits in the CRC */ template -inline CRC::Table::Table(const Parameters & parameters) : - parameters(parameters) +inline CRC::Table::Table(const Parameters & params) : + parameters(params) { InitTable(); } @@ -334,13 +354,13 @@ inline CRC::Table::Table(const Parameters #ifdef CRCPP_USE_CPP11 /** @brief Constructs a CRC table from a set of CRC parameters - @param[in] parameters CRC parameters + @param[in] params CRC parameters @tparam CRCType Integer type for storing the CRC result @tparam CRCWidth Number of bits in the CRC */ template -inline CRC::Table::Table(Parameters && parameters) : - parameters(::std::move(parameters)) +inline CRC::Table::Table(Parameters && params) : + parameters(::std::move(params)) { InitTable(); } @@ -395,7 +415,8 @@ inline void CRC::Table::InitTable() static crcpp_constexpr CRCType BIT_MASK((CRCType(1) << (CRCWidth - CRCType(1))) | ((CRCType(1) << (CRCWidth - CRCType(1))) - CRCType(1))); - static crcpp_constexpr CRCType SHIFT(CRC::BoundedConstexprValue(CHAR_BIT - CRCWidth)); + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CHAR_BIT >= CRCWidth) ? static_cast(CHAR_BIT - CRCWidth) : 0); CRCType crc; unsigned char byte = 0; @@ -414,7 +435,7 @@ inline void CRC::Table::InitTable() { // Undo the special operation at the end of the CalculateRemainder() // function for non-reflected CRCs < CHAR_BIT. - crc <<= SHIFT; + crc = static_cast(crc << SHIFT); } table[byte] = crc; @@ -425,7 +446,7 @@ inline void CRC::Table::InitTable() /** @brief Computes a CRC. @param[in] data Data over which CRC will be computed - @param[in] size Size of the data + @param[in] size Size of the data, in bytes @param[in] parameters CRC parameters @tparam CRCType Integer type for storing the CRC result @tparam CRCWidth Number of bits in the CRC @@ -444,7 +465,7 @@ inline CRCType CRC::Calculate(const void * data, crcpp_size size, const Paramete @brief Appends additional data to a previous CRC calculation. @note This function can be used to compute multi-part CRCs. @param[in] data Data over which CRC will be computed - @param[in] size Size of the data + @param[in] size Size of the data, in bytes @param[in] parameters CRC parameters @param[in] crc CRC from a previous calculation @tparam CRCType Integer type for storing the CRC result @@ -466,7 +487,7 @@ inline CRCType CRC::Calculate(const void * data, crcpp_size size, const Paramete /** @brief Computes a CRC via a lookup table. @param[in] data Data over which CRC will be computed - @param[in] size Size of the data + @param[in] size Size of the data, in bytes @param[in] lookupTable CRC lookup table @tparam CRCType Integer type for storing the CRC result @tparam CRCWidth Number of bits in the CRC @@ -488,7 +509,7 @@ inline CRCType CRC::Calculate(const void * data, crcpp_size size, const Table(remainder, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); } +/** + @brief Computes a CRC. + @param[in] data Data over which CRC will be computed + @param[in] size Size of the data, in bits + @param[in] parameters CRC parameters + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC +*/ +template +inline CRCType CRC::CalculateBits(const void * data, crcpp_size size, const Parameters & parameters) +{ + CRCType remainder = parameters.initialValue; + + // Calculate the remainder on a whole number of bytes first, then call + // a special-case function for the remaining bits. + crcpp_size wholeNumberOfBytes = size / CHAR_BIT; + if (wholeNumberOfBytes > 0) + { + remainder = CalculateRemainder(data, wholeNumberOfBytes, parameters, remainder); + } + + crcpp_size remainingNumberOfBits = size % CHAR_BIT; + if (remainingNumberOfBits != 0) + { + unsigned char lastByte = *(reinterpret_cast(data) + wholeNumberOfBytes); + remainder = CalculateRemainderBits(lastByte, remainingNumberOfBits, parameters, remainder); + } + + // No need to mask the remainder here; the mask will be applied in the Finalize() function. + + return Finalize(remainder, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); +} +/** + @brief Appends additional data to a previous CRC calculation. + @note This function can be used to compute multi-part CRCs. + @param[in] data Data over which CRC will be computed + @param[in] size Size of the data, in bits + @param[in] parameters CRC parameters + @param[in] crc CRC from a previous calculation + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC +*/ +template +inline CRCType CRC::CalculateBits(const void * data, crcpp_size size, const Parameters & parameters, CRCType crc) +{ + CRCType remainder = UndoFinalize(crc, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); + + // Calculate the remainder on a whole number of bytes first, then call + // a special-case function for the remaining bits. + crcpp_size wholeNumberOfBytes = size / CHAR_BIT; + if (wholeNumberOfBytes > 0) + { + remainder = CalculateRemainder(data, wholeNumberOfBytes, parameters, parameters.initialValue); + } + + crcpp_size remainingNumberOfBits = size % CHAR_BIT; + if (remainingNumberOfBits != 0) + { + unsigned char lastByte = *(reinterpret_cast(data) + wholeNumberOfBytes); + remainder = CalculateRemainderBits(lastByte, remainingNumberOfBits, parameters, remainder); + } + + // No need to mask the remainder here; the mask will be applied in the Finalize() function. + + return Finalize(remainder, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); +} + +/** + @brief Computes a CRC via a lookup table. + @param[in] data Data over which CRC will be computed + @param[in] size Size of the data, in bits + @param[in] lookupTable CRC lookup table + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC +*/ +template +inline CRCType CRC::CalculateBits(const void * data, crcpp_size size, const Table & lookupTable) +{ + const Parameters & parameters = lookupTable.GetParameters(); + + CRCType remainder = parameters.initialValue; + + // Calculate the remainder on a whole number of bytes first, then call + // a special-case function for the remaining bits. + crcpp_size wholeNumberOfBytes = size / CHAR_BIT; + if (wholeNumberOfBytes > 0) + { + remainder = CalculateRemainder(data, wholeNumberOfBytes, lookupTable, remainder); + } + + crcpp_size remainingNumberOfBits = size % CHAR_BIT; + if (remainingNumberOfBits != 0) + { + unsigned char lastByte = *(reinterpret_cast(data) + wholeNumberOfBytes); + remainder = CalculateRemainderBits(lastByte, remainingNumberOfBits, parameters, remainder); + } + + // No need to mask the remainder here; the mask will be applied in the Finalize() function. + + return Finalize(remainder, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); +} + +/** + @brief Appends additional data to a previous CRC calculation using a lookup table. + @note This function can be used to compute multi-part CRCs. + @param[in] data Data over which CRC will be computed + @param[in] size Size of the data, in bits + @param[in] lookupTable CRC lookup table + @param[in] crc CRC from a previous calculation + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC +*/ +template +inline CRCType CRC::CalculateBits(const void * data, crcpp_size size, const Table & lookupTable, CRCType crc) +{ + const Parameters & parameters = lookupTable.GetParameters(); + + CRCType remainder = UndoFinalize(crc, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); + + // Calculate the remainder on a whole number of bytes first, then call + // a special-case function for the remaining bits. + crcpp_size wholeNumberOfBytes = size / CHAR_BIT; + if (wholeNumberOfBytes > 0) + { + remainder = CalculateRemainder(data, wholeNumberOfBytes, lookupTable, parameters.initialValue); + } + + crcpp_size remainingNumberOfBits = size % CHAR_BIT; + if (remainingNumberOfBits > 0) + { + unsigned char lastByte = *(reinterpret_cast(data) + wholeNumberOfBytes); + remainder = CalculateRemainderBits(lastByte, remainingNumberOfBits, parameters, remainder); + } + + // No need to mask the remainder here; the mask will be applied in the Finalize() function. + + return Finalize(remainder, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); +} + /** @brief Reflects (i.e. reverses the bits within) an integer value. @param[in] value Value to reflect @@ -523,8 +687,8 @@ inline IntegerType CRC::Reflect(IntegerType value, crcpp_uint16 numBits) for (crcpp_uint16 i = 0; i < numBits; ++i) { - reversedValue = (reversedValue << 1) | (value & 1); - value >>= 1; + reversedValue = static_cast((reversedValue << 1) | (value & 1)); + value = static_cast(value >> 1); } return reversedValue; @@ -591,7 +755,7 @@ inline CRCType CRC::UndoFinalize(CRCType crc, CRCType finalXOR, bool reflectOutp /** @brief Computes a CRC remainder. @param[in] data Data over which the remainder will be computed - @param[in] size Size of the data + @param[in] size Size of the data, in bytes @param[in] parameters CRC parameters @param[in] remainder Running CRC remainder. Can be an initial value or the result of a previous CRC remainder calculation. @tparam CRCType Integer type for storing the CRC result @@ -620,7 +784,7 @@ inline CRCType CRC::CalculateRemainder(const void * data, crcpp_size size, const CRCType polynomial = CRC::Reflect(parameters.polynomial, CRCWidth); while (size--) { - remainder ^= *current++; + remainder = static_cast(remainder ^ *current++); // An optimizing compiler might choose to unroll this loop. for (crcpp_size i = 0; i < CHAR_BIT; ++i) @@ -631,9 +795,9 @@ inline CRCType CRC::CalculateRemainder(const void * data, crcpp_size size, const // remainder = (remainder >> 1) ^ polynomial; // else // remainder >>= 1; - remainder = (remainder >> 1) ^ ((remainder & 1) * polynomial); + remainder = static_cast((remainder >> 1) ^ ((remainder & 1) * polynomial)); #else - remainder = (remainder & 1) ? ((remainder >> 1) ^ polynomial) : (remainder >> 1); + remainder = static_cast((remainder & 1) ? ((remainder >> 1) ^ polynomial) : (remainder >> 1)); #endif } } @@ -644,11 +808,12 @@ inline CRCType CRC::CalculateRemainder(const void * data, crcpp_size size, const #ifndef CRCPP_BRANCHLESS static crcpp_constexpr CRCType CRC_HIGHEST_BIT_MASK(CRCType(1) << CRC_WIDTH_MINUS_ONE); #endif - static crcpp_constexpr CRCType SHIFT(BoundedConstexprValue(CRCWidth - CHAR_BIT)); + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CRCWidth >= CHAR_BIT) ? static_cast(CRCWidth - CHAR_BIT) : 0); while (size--) { - remainder ^= (static_cast(*current++) << SHIFT); + remainder = static_cast(remainder ^ (static_cast(*current++) << SHIFT)); // An optimizing compiler might choose to unroll this loop. for (crcpp_size i = 0; i < CHAR_BIT; ++i) @@ -659,9 +824,9 @@ inline CRCType CRC::CalculateRemainder(const void * data, crcpp_size size, const // remainder = (remainder << 1) ^ parameters.polynomial; // else // remainder <<= 1; - remainder = (remainder << 1) ^ (((remainder >> CRC_WIDTH_MINUS_ONE) & 1) * parameters.polynomial); + remainder = static_cast((remainder << 1) ^ (((remainder >> CRC_WIDTH_MINUS_ONE) & 1) * parameters.polynomial)); #else - remainder = (remainder & CRC_HIGHEST_BIT_MASK) ? ((remainder << 1) ^ parameters.polynomial) : (remainder << 1); + remainder = static_cast((remainder & CRC_HIGHEST_BIT_MASK) ? ((remainder << 1) ^ parameters.polynomial) : (remainder << 1)); #endif } } @@ -672,14 +837,15 @@ inline CRCType CRC::CalculateRemainder(const void * data, crcpp_size size, const #ifndef CRCPP_BRANCHLESS static crcpp_constexpr CRCType CHAR_BIT_HIGHEST_BIT_MASK(CRCType(1) << CHAR_BIT_MINUS_ONE); #endif - static crcpp_constexpr CRCType SHIFT(BoundedConstexprValue(CHAR_BIT - CRCWidth)); + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CHAR_BIT >= CRCWidth) ? static_cast(CHAR_BIT - CRCWidth) : 0); - CRCType polynomial = parameters.polynomial << SHIFT; - remainder <<= SHIFT; + CRCType polynomial = static_cast(parameters.polynomial << SHIFT); + remainder = static_cast(remainder << SHIFT); while (size--) { - remainder ^= *current++; + remainder = static_cast(remainder ^ *current++); // An optimizing compiler might choose to unroll this loop. for (crcpp_size i = 0; i < CHAR_BIT; ++i) @@ -690,14 +856,14 @@ inline CRCType CRC::CalculateRemainder(const void * data, crcpp_size size, const // remainder = (remainder << 1) ^ polynomial; // else // remainder <<= 1; - remainder = (remainder << 1) ^ (((remainder >> CHAR_BIT_MINUS_ONE) & 1) * polynomial); + remainder = static_cast((remainder << 1) ^ (((remainder >> CHAR_BIT_MINUS_ONE) & 1) * polynomial)); #else - remainder = (remainder & CHAR_BIT_HIGHEST_BIT_MASK) ? ((remainder << 1) ^ polynomial) : (remainder << 1); + remainder = static_cast((remainder & CHAR_BIT_HIGHEST_BIT_MASK) ? ((remainder << 1) ^ polynomial) : (remainder << 1)); #endif } } - remainder >>= SHIFT; + remainder = static_cast(remainder >> SHIFT); } return remainder; @@ -706,7 +872,7 @@ inline CRCType CRC::CalculateRemainder(const void * data, crcpp_size size, const /** @brief Computes a CRC remainder using lookup table. @param[in] data Data over which the remainder will be computed - @param[in] size Size of the data + @param[in] size Size of the data, in bytes @param[in] lookupTable CRC lookup table @param[in] remainder Running CRC remainder. Can be an initial value or the result of a previous CRC remainder calculation. @tparam CRCType Integer type for storing the CRC result @@ -726,33 +892,31 @@ inline CRCType CRC::CalculateRemainder(const void * data, crcpp_size size, const // Disable warning about data loss when doing (remainder >> CHAR_BIT) when // remainder is one byte long. The algorithm is still correct in this case, // though it's possible that one additional machine instruction will be executed. -# if defined(_MSC_VER) # pragma warning (push) # pragma warning (disable : 4333) -# endif #endif - remainder = (remainder >> CHAR_BIT) ^ lookupTable[static_cast(remainder ^ *current++)]; + remainder = static_cast((remainder >> CHAR_BIT) ^ lookupTable[static_cast(remainder ^ *current++)]); #if defined(WIN32) || defined(_WIN32) || defined(WINCE) -# if defined(_MSC_VER) # pragma warning (pop) -# endif #endif } } else if (CRCWidth >= CHAR_BIT) { - static crcpp_constexpr CRCType SHIFT(BoundedConstexprValue(CRCWidth - CHAR_BIT)); + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CRCWidth >= CHAR_BIT) ? static_cast(CRCWidth - CHAR_BIT) : 0); while (size--) { - remainder = (remainder << CHAR_BIT) ^ lookupTable[static_cast((remainder >> SHIFT) ^ *current++)]; + remainder = static_cast((remainder << CHAR_BIT) ^ lookupTable[static_cast((remainder >> SHIFT) ^ *current++)]); } } else { - static crcpp_constexpr CRCType SHIFT(BoundedConstexprValue(CHAR_BIT - CRCWidth)); + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CHAR_BIT >= CRCWidth) ? static_cast(CHAR_BIT - CRCWidth) : 0); - remainder <<= SHIFT; + remainder = static_cast(remainder << SHIFT); while (size--) { @@ -760,26 +924,94 @@ inline CRCType CRC::CalculateRemainder(const void * data, crcpp_size size, const remainder = lookupTable[static_cast(remainder ^ *current++)]; } - remainder >>= SHIFT; + remainder = static_cast(remainder >> SHIFT); } return remainder; } -/** - @brief Function to force a compile-time expression to be >= 0. - @note This function is used to avoid compiler warnings because all constexpr values are evaluated - in a function even in a branch will never be executed. This also means we don't need pragmas - to get rid of warnings, but it still can be computed at compile-time. Win-win! - @param[in] x Compile-time expression to bound - @tparam CRCType Integer type for storing the CRC result - @tparam CRCWidth Number of bits in the CRC - @return Non-negative compile-time expression -*/ -template -inline crcpp_constexpr IntegerType CRC::BoundedConstexprValue(IntegerType x) +template +inline CRCType CRC::CalculateRemainderBits(unsigned char byte, crcpp_size numBits, const Parameters & parameters, CRCType remainder) { - return (x < IntegerType(0)) ? IntegerType(0) : x; + // Slightly different implementations based on the parameters. The current implementations try to eliminate as much + // computation from the inner loop (looping over each bit) as possible. + if (parameters.reflectInput) + { + CRCType polynomial = CRC::Reflect(parameters.polynomial, CRCWidth); + remainder = static_cast(remainder ^ byte); + + // An optimizing compiler might choose to unroll this loop. + for (crcpp_size i = 0; i < numBits; ++i) + { +#ifdef CRCPP_BRANCHLESS + // Clever way to avoid a branch at the expense of a multiplication. This code is equivalent to the following: + // if (remainder & 1) + // remainder = (remainder >> 1) ^ polynomial; + // else + // remainder >>= 1; + remainder = static_cast((remainder >> 1) ^ ((remainder & 1) * polynomial)); +#else + remainder = static_cast((remainder & 1) ? ((remainder >> 1) ^ polynomial) : (remainder >> 1)); +#endif + } + } + else if (CRCWidth >= CHAR_BIT) + { + static crcpp_constexpr CRCType CRC_WIDTH_MINUS_ONE(CRCWidth - CRCType(1)); +#ifndef CRCPP_BRANCHLESS + static crcpp_constexpr CRCType CRC_HIGHEST_BIT_MASK(CRCType(1) << CRC_WIDTH_MINUS_ONE); +#endif + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CRCWidth >= CHAR_BIT) ? static_cast(CRCWidth - CHAR_BIT) : 0); + + remainder = static_cast(remainder ^ (static_cast(byte) << SHIFT)); + + // An optimizing compiler might choose to unroll this loop. + for (crcpp_size i = 0; i < numBits; ++i) + { +#ifdef CRCPP_BRANCHLESS + // Clever way to avoid a branch at the expense of a multiplication. This code is equivalent to the following: + // if (remainder & CRC_HIGHEST_BIT_MASK) + // remainder = (remainder << 1) ^ parameters.polynomial; + // else + // remainder <<= 1; + remainder = static_cast((remainder << 1) ^ (((remainder >> CRC_WIDTH_MINUS_ONE) & 1) * parameters.polynomial)); +#else + remainder = static_cast((remainder & CRC_HIGHEST_BIT_MASK) ? ((remainder << 1) ^ parameters.polynomial) : (remainder << 1)); +#endif + } + } + else + { + static crcpp_constexpr CRCType CHAR_BIT_MINUS_ONE(CHAR_BIT - 1); +#ifndef CRCPP_BRANCHLESS + static crcpp_constexpr CRCType CHAR_BIT_HIGHEST_BIT_MASK(CRCType(1) << CHAR_BIT_MINUS_ONE); +#endif + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CHAR_BIT >= CRCWidth) ? static_cast(CHAR_BIT - CRCWidth) : 0); + + CRCType polynomial = static_cast(parameters.polynomial << SHIFT); + remainder = static_cast((remainder << SHIFT) ^ byte); + + // An optimizing compiler might choose to unroll this loop. + for (crcpp_size i = 0; i < numBits; ++i) + { +#ifdef CRCPP_BRANCHLESS + // Clever way to avoid a branch at the expense of a multiplication. This code is equivalent to the following: + // if (remainder & CHAR_BIT_HIGHEST_BIT_MASK) + // remainder = (remainder << 1) ^ polynomial; + // else + // remainder <<= 1; + remainder = static_cast((remainder << 1) ^ (((remainder >> CHAR_BIT_MINUS_ONE) & 1) * polynomial)); +#else + remainder = static_cast((remainder & CHAR_BIT_HIGHEST_BIT_MASK) ? ((remainder << 1) ^ polynomial) : (remainder << 1)); +#endif + } + + remainder = static_cast(remainder >> SHIFT); + } + + return remainder; } #ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS @@ -909,6 +1141,25 @@ inline const CRC::Parameters & CRC::CRC_6_ITU() return parameters; } +/** + @brief Returns a set of parameters for CRC-6 NR. + @note The parameters are static and are delayed-constructed to reduce memory + footprint. + @note CRC-6 NR has the following parameters and check value: + - polynomial = 0x21 + - initial value = 0x00 + - final XOR = 0x00 + - reflect input = false + - reflect output = false + - check value = 0x15 + @return CRC-6 NR parameters +*/ +inline const CRC::Parameters & CRC::CRC_6_NR() +{ + static const Parameters parameters = { 0x21, 0x00, 0x00, false, false }; + return parameters; +} + /** @brief Returns a set of parameters for CRC-7 JEDEC. @note The parameters are static and are delayed-constructed to reduce memory footprint. @@ -1001,6 +1252,24 @@ inline const CRC::Parameters & CRC::CRC_8_WCDMA() return parameters; } +/** + @brief Returns a set of parameters for CRC-8 LTE. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-8 LTE has the following parameters and check value: + - polynomial = 0x9B + - initial value = 0x00 + - final XOR = 0x00 + - reflect input = false + - reflect output = false + - check value = 0xEA + @return CRC-8 LTE parameters +*/ +inline const CRC::Parameters & CRC::CRC_8_LTE() +{ + static const Parameters parameters = { 0x9B, 0x00, 0x00, false, false }; + return parameters; +} + /** @brief Returns a set of parameters for CRC-10 ITU. @note The parameters are static and are delayed-constructed to reduce memory footprint. @@ -1055,6 +1324,25 @@ inline const CRC::Parameters & CRC::CRC_11() return parameters; } +/** + @brief Returns a set of parameters for CRC-11 NR. + @note The parameters are static and are delayed-constructed to reduce memory + footprint. + @note CRC-11 NR has the following parameters and check value: + - polynomial = 0x621 + - initial value = 0x000 + - final XOR = 0x000 + - reflect input = false + - reflect output = false + - check value = 0x5CA + @return CRC-11 NR parameters +*/ +inline const CRC::Parameters & CRC::CRC_11_NR() +{ + static const Parameters parameters = { 0x621, 0x000, 0x000, false, false }; + return parameters; +} + /** @brief Returns a set of parameters for CRC-12 CDMA2000. @note The parameters are static and are delayed-constructed to reduce memory footprint. @@ -1218,6 +1506,24 @@ inline const CRC::Parameters & CRC::CRC_16_CCITTFALSE() return parameters; } +/** + @brief Returns a set of parameters for CRC-16 MCRF4XX. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 MCRF4XX has the following parameters and check value: + - polynomial = 0x1021 + - initial value = 0xFFFF + - final XOR = 0x0000 + - reflect input = true + - reflect output = true + - check value = 0x6F91 + @return CRC-16 MCRF4XX parameters +*/ +inline const CRC::Parameters & CRC::CRC_16_MCRF4XX() +{ + static const Parameters parameters = { 0x1021, 0xFFFF, 0x0000, true, true}; + return parameters; +} + #ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS /** @brief Returns a set of parameters for CRC-16 CDMA2000. @@ -1237,6 +1543,24 @@ inline const CRC::Parameters & CRC::CRC_16_CDMA2000() return parameters; } +/** + @brief Returns a set of parameters for CRC-16 CMS. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 CMS has the following parameters and check value: + - polynomial = 0x8005 + - initial value = 0xFFFF + - final XOR = 0x0000 + - reflect input = false + - reflect output = false + - check value = 0xAEE7 + @return CRC-16 CMS parameters +*/ +inline const CRC::Parameters & CRC::CRC_16_CMS() +{ + static const Parameters parameters = { 0x8005, 0xFFFF, 0x0000, false, false }; + return parameters; +} + /** @brief Returns a set of parameters for CRC-16 DECT-R (aka CRC-16 R-CRC). @note The parameters are static and are delayed-constructed to reduce memory footprint. @@ -1400,6 +1724,7 @@ inline const CRC::Parameters & CRC::CRC_16_USB() static const Parameters parameters = { 0x8005, 0xFFFF, 0xFFFF, true, true }; return parameters; } + #endif // CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS /** @@ -1529,6 +1854,63 @@ inline const CRC::Parameters & CRC::CRC_24_FLEXRAYB() return parameters; } +/** + @brief Returns a set of parameters for CRC-24 LTE-A/NR-A. + @note The parameters are static and are delayed-constructed to reduce memory + footprint. + @note CRC-24 LTE-A has the following parameters and check value: + - polynomial = 0x864CFB + - initial value = 0x000000 + - final XOR = 0x000000 + - reflect input = false + - reflect output = false + - check value = 0xCDE703 + @return CRC-24 LTE-A parameters +*/ +inline const CRC::Parameters & CRC::CRC_24_LTEA() +{ + static const Parameters parameters = { 0x864CFB, 0x000000, 0x000000, false, false }; + return parameters; +} + +/** + @brief Returns a set of parameters for CRC-24 LTE-B/NR-B. + @note The parameters are static and are delayed-constructed to reduce memory + footprint. + @note CRC-24 LTE-B has the following parameters and check value: + - polynomial = 0x800063 + - initial value = 0x000000 + - final XOR = 0x000000 + - reflect input = false + - reflect output = false + - check value = 0x23EF52 + @return CRC-24 LTE-B parameters +*/ +inline const CRC::Parameters & CRC::CRC_24_LTEB() +{ + static const Parameters parameters = { 0x800063, 0x000000, 0x000000, false, false }; + return parameters; +} + +/** + @brief Returns a set of parameters for CRC-24 NR-C. + @note The parameters are static and are delayed-constructed to reduce memory + footprint. + @note CRC-24 NR-C has the following parameters and check value: + - polynomial = 0xB2B117 + - initial value = 0x000000 + - final XOR = 0x000000 + - reflect input = false + - reflect output = false + - check value = 0xF48279 + @return CRC-24 NR-C parameters +*/ +inline const CRC::Parameters & CRC::CRC_24_NRC() +{ + static const Parameters parameters = { 0xB2B117, 0x000000, 0x000000, false, false }; + return parameters; +} + /** @brief Returns a set of parameters for CRC-30 CDMA. @note The parameters are static and are delayed-constructed to reduce memory footprint. diff --git a/src/3rdParty/libE57Format/include/CMakeLists.txt b/src/3rdParty/libE57Format/include/CMakeLists.txt index 3fafb3ca4280b..c47a5584c58a9 100644 --- a/src/3rdParty/libE57Format/include/CMakeLists.txt +++ b/src/3rdParty/libE57Format/include/CMakeLists.txt @@ -3,27 +3,28 @@ target_sources( ${PROJECT_NAME} PRIVATE - ${CMAKE_CURRENT_LIST_DIR}/E57Exception.h - ${CMAKE_CURRENT_LIST_DIR}/E57Format.h - ${CMAKE_CURRENT_LIST_DIR}/E57SimpleData.h - ${CMAKE_CURRENT_LIST_DIR}/E57SimpleReader.h - ${CMAKE_CURRENT_LIST_DIR}/E57SimpleWriter.h + E57Exception.h + E57Format.h + E57SimpleData.h + E57SimpleReader.h + E57SimpleWriter.h + E57Version.h ) -#install( -# FILES -# E57Format.h -# E57Exception.h -# E57SimpleData.h -# E57SimpleReader.h -# E57SimpleWriter.h -# DESTINATION -# include/E57Format -#) +install( + FILES + E57Format.h + E57Exception.h + E57SimpleData.h + E57SimpleReader.h + E57SimpleWriter.h + E57Version.h + DESTINATION + include/E57Format +) target_include_directories( ${PROJECT_NAME} PUBLIC $ $ ) - diff --git a/src/3rdParty/libE57Format/include/E57Exception.h b/src/3rdParty/libE57Format/include/E57Exception.h index 7f25a016af2c7..9ce6d6d73e4f6 100644 --- a/src/3rdParty/libE57Format/include/E57Exception.h +++ b/src/3rdParty/libE57Format/include/E57Exception.h @@ -27,110 +27,367 @@ #pragma once +/// @file E57Exception.h Exception handling for E57 API. + #include #include #include #include "E57Export.h" +#ifndef E57_ENABLE_DIAGNOSTIC_OUTPUT +// Used to mark unused parameters to indicate intent and suppress warnings. +#define UNUSED( expr ) (void)( expr ) +#endif + +// C++14 does not support the [[deprecated]] attribute on enumerators. +// Turn on enumerator deprecation notices if we are compiling with C++17 or later. +#if ( ( defined( _MSVC_LANG ) && _MSVC_LANG >= 201703L ) || __cplusplus >= 201703L ) +#define DEPRECATED_ENUM( str ) [[deprecated( str )]] +#else +#define DEPRECATED_ENUM( str ) +#endif + namespace e57 { - //! @brief Numeric error identifiers used in E57Exception + /// @brief Numeric error identifiers used in E57Exception enum ErrorCode { - // N.B. *** When changing error strings here, remember to update the error - // strings in E57Exception.cpp **** - E57_SUCCESS = 0, //!< operation was successful - E57_ERROR_BAD_CV_HEADER = 1, //!< a CompressedVector binary header was bad - E57_ERROR_BAD_CV_PACKET = 2, //!< a CompressedVector binary packet was bad - E57_ERROR_CHILD_INDEX_OUT_OF_BOUNDS = 3, //!< a numerical index identifying a child was out of bounds - E57_ERROR_SET_TWICE = 4, //!< attempted to set an existing child element to a new value - E57_ERROR_HOMOGENEOUS_VIOLATION = 5, //!< attempted to add an E57 Element that would have made the children - //!< of a homogeneous Vector have different types - E57_ERROR_VALUE_NOT_REPRESENTABLE = 6, //!< a value could not be represented in the requested type - E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE = 7, //!< after scaling the result could not be represented in the - //!< requested type - E57_ERROR_REAL64_TOO_LARGE = 8, //!< a 64 bit IEEE float was too large to store in a 32 bit IEEE float - E57_ERROR_EXPECTING_NUMERIC = 9, //!< Expecting numeric representation in user's buffer, found ustring - E57_ERROR_EXPECTING_USTRING = 10, //!< Expecting string representation in user's buffer, found numeric - E57_ERROR_INTERNAL = 11, //!< An unrecoverable inconsistent internal state was detected - E57_ERROR_BAD_XML_FORMAT = 12, //!< E57 primitive not encoded in XML correctly - E57_ERROR_XML_PARSER = 13, //!< XML not well formed - E57_ERROR_BAD_API_ARGUMENT = 14, //!< bad API function argument provided by user - E57_ERROR_FILE_IS_READ_ONLY = 15, //!< can't modify read only file - E57_ERROR_BAD_CHECKSUM = 16, //!< checksum mismatch, file is corrupted - E57_ERROR_OPEN_FAILED = 17, //!< open() failed - E57_ERROR_CLOSE_FAILED = 18, //!< close() failed - E57_ERROR_READ_FAILED = 19, //!< read() failed - E57_ERROR_WRITE_FAILED = 20, //!< write() failed - E57_ERROR_LSEEK_FAILED = 21, //!< lseek() failed - E57_ERROR_PATH_UNDEFINED = 22, //!< E57 element path well formed but not defined - E57_ERROR_BAD_BUFFER = 23, //!< bad SourceDestBuffer - E57_ERROR_NO_BUFFER_FOR_ELEMENT = 24, //!< no buffer specified for an element in CompressedVectorNode during - //!< write - E57_ERROR_BUFFER_SIZE_MISMATCH = 25, //!< SourceDestBuffers not all same size - E57_ERROR_BUFFER_DUPLICATE_PATHNAME = 26, //!< duplicate pathname in CompressedVectorNode read/write - E57_ERROR_BAD_FILE_SIGNATURE = 27, //!< file signature not "ASTM-E57" - E57_ERROR_UNKNOWN_FILE_VERSION = 28, //!< incompatible file version - E57_ERROR_BAD_FILE_LENGTH = 29, //!< size in file header not same as actual - E57_ERROR_XML_PARSER_INIT = 30, //!< XML parser failed to initialize - E57_ERROR_DUPLICATE_NAMESPACE_PREFIX = 31, //!< namespace prefix already defined - E57_ERROR_DUPLICATE_NAMESPACE_URI = 32, //!< namespace URI already defined - E57_ERROR_BAD_PROTOTYPE = 33, //!< bad prototype in CompressedVectorNode - E57_ERROR_BAD_CODECS = 34, //!< bad codecs in CompressedVectorNode - E57_ERROR_VALUE_OUT_OF_BOUNDS = 35, //!< element value out of min/max bounds - E57_ERROR_CONVERSION_REQUIRED = 36, //!< conversion required to assign element value, but not requested - E57_ERROR_BAD_PATH_NAME = 37, //!< E57 path name is not well formed - E57_ERROR_NOT_IMPLEMENTED = 38, //!< functionality not implemented - E57_ERROR_BAD_NODE_DOWNCAST = 39, //!< bad downcast from Node to specific node type - E57_ERROR_WRITER_NOT_OPEN = 40, //!< CompressedVectorWriter is no longer open - E57_ERROR_READER_NOT_OPEN = 41, //!< CompressedVectorReader is no longer open - E57_ERROR_NODE_UNATTACHED = 42, //!< node is not yet attached to tree of ImageFile - E57_ERROR_ALREADY_HAS_PARENT = 43, //!< node already has a parent - E57_ERROR_DIFFERENT_DEST_IMAGEFILE = 44, //!< nodes were constructed with different destImageFiles - E57_ERROR_IMAGEFILE_NOT_OPEN = 45, //!< destImageFile is no longer open - E57_ERROR_BUFFERS_NOT_COMPATIBLE = 46, //!< SourceDestBuffers not compatible with previously given ones - E57_ERROR_TOO_MANY_WRITERS = 47, //!< too many open CompressedVectorWriters of an ImageFile - E57_ERROR_TOO_MANY_READERS = 48, //!< too many open CompressedVectorReaders of an ImageFile - E57_ERROR_BAD_CONFIGURATION = 49, //!< bad configuration string - E57_ERROR_INVARIANCE_VIOLATION = 50 //!< class invariance constraint violation in debug mode + // NOTE: When changing error strings here, remember to update the error strings in + // E57Exception.cpp + + Success = 0, ///< operation was successful + + ErrorBadCVHeader = 1, ///< a CompressedVector binary header was bad + ErrorBadCVPacket = 2, ///< a CompressedVector binary packet was bad + ErrorChildIndexOutOfBounds = 3, ///< a numerical index identifying a child was out of bounds + ErrorSetTwice = 4, ///< attempted to set an existing child element to a new value + + /// @brief attempted to add an element that would have made the children of a homogeneous + /// ::TypeVector have different types + ErrorHomogeneousViolation = 5, + + /// a value could not be represented in the requested type + ErrorValueNotRepresentable = 6, + + /// after scaling the result could not be represented in the requested type + ErrorScaledValueNotRepresentable = 7, + + /// a 64 bit IEEE float was too large to store in a 32 bit IEEE float + ErrorReal64TooLarge = 8, + + /// expecting numeric representation in user's buffer, found ustring + ErrorExpectingNumeric = 9, + + /// expecting string representation in user's buffer, found numeric + ErrorExpectingUString = 10, + + ErrorInternal = 11, ///< An unrecoverable inconsistent internal state was detected + ErrorBadXMLFormat = 12, ///< E57 primitive not encoded in XML correctly + ErrorXMLParser = 13, ///< XML not well formed + ErrorBadAPIArgument = 14, ///< bad API function argument provided by user + ErrorFileReadOnly = 15, ///< can't modify read only file + ErrorBadChecksum = 16, ///< checksum mismatch, file is corrupted + ErrorOpenFailed = 17, ///< open() failed + ErrorCloseFailed = 18, ///< close() failed + ErrorReadFailed = 19, ///< read() failed + ErrorWriteFailed = 20, ///< write() failed + ErrorSeekFailed = 21, ///< lseek() failed + ErrorPathUndefined = 22, ///< element path well formed but not defined + ErrorBadBuffer = 23, ///< bad SourceDestBuffer + + /// no buffer specified for an element in CompressedVectorNode during write + ErrorNoBufferForElement = 24, + + ErrorBufferSizeMismatch = 25, ///< SourceDestBuffers not all same size + ErrorBufferDuplicatePathName = 26, ///< duplicate pathname in CompressedVectorNode read/write + ErrorBadFileSignature = 27, ///< file signature not "ASTM-E57" + ErrorUnknownFileVersion = 28, ///< incompatible file version + ErrorBadFileLength = 29, ///< size in file header not same as actual + ErrorXMLParserInit = 30, ///< XML parser failed to initialize + ErrorDuplicateNamespacePrefix = 31, ///< namespace prefix already defined + ErrorDuplicateNamespaceURI = 32, ///< namespace URI already defined + ErrorBadPrototype = 33, ///< bad prototype in CompressedVectorNode + ErrorBadCodecs = 34, ///< bad codecs in CompressedVectorNode + ErrorValueOutOfBounds = 35, ///< element value out of min/max bounds + + /// conversion required to assign element value, but not requested + ErrorConversionRequired = 36, + + ErrorBadPathName = 37, ///< E57 path name is not well formed + ErrorNotImplemented = 38, ///< functionality not implemented + ErrorBadNodeDowncast = 39, ///< bad downcast from Node to specific node type + ErrorWriterNotOpen = 40, ///< CompressedVectorWriter is no longer open + ErrorReaderNotOpen = 41, ///< CompressedVectorReader is no longer open + ErrorNodeUnattached = 42, ///< node is not yet attached to tree of ImageFile + ErrorAlreadyHasParent = 43, ///< node already has a parent + ErrorDifferentDestImageFile = 44, ///< nodes were constructed with different destImageFiles + ErrorImageFileNotOpen = 45, ///< destImageFile is no longer open + + /// SourceDestBuffers not compatible with previously given ones + ErrorBuffersNotCompatible = 46, + + ErrorTooManyWriters = 47, ///< too many open CompressedVectorWriters of an ImageFile + ErrorTooManyReaders = 48, ///< too many open CompressedVectorReaders of an ImageFile + ErrorBadConfiguration = 49, ///< bad configuration string + ErrorInvarianceViolation = 50, ///< class invariance constraint violation in debug mode + + /// an invalid node type was passed in Data3D pointFields + ErrorInvalidNodeType = 51, + + /// passed an invalid value in Data3D pointFields + ErrorInvalidData3DValue = 52, + + /// @deprecated Will be removed in 4.0. Use e57::Success. + E57_SUCCESS DEPRECATED_ENUM( "Will be removed in 4.0. Use Success." ) = Success, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadCVHeader. + E57_ERROR_BAD_CV_HEADER DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorBadCVHeader." ) = + ErrorBadCVHeader, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadCVPacket. + E57_ERROR_BAD_CV_PACKET DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorBadCVPacket." ) = + ErrorBadCVPacket, + /// @deprecated Will be removed in 4.0. Use e57::ErrorChildIndexOutOfBounds. + E57_ERROR_CHILD_INDEX_OUT_OF_BOUNDS DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorChildIndexOutOfBounds." ) = ErrorChildIndexOutOfBounds, + /// @deprecated Will be removed in 4.0. Use e57::ErrorSetTwice. + E57_ERROR_SET_TWICE DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorSetTwice." ) = + ErrorSetTwice, + /// @deprecated Will be removed in 4.0. Use e57::ErrorHomogeneousViolation. + E57_ERROR_HOMOGENEOUS_VIOLATION DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorHomogeneousViolation." ) = ErrorHomogeneousViolation, + /// @deprecated Will be removed in 4.0. Use e57::ErrorValueNotRepresentable. + E57_ERROR_VALUE_NOT_REPRESENTABLE DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorValueNotRepresentable." ) = ErrorValueNotRepresentable, + /// @deprecated Will be removed in 4.0. Use e57::ErrorScaledValueNotRepresentable. + E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorScaledValueNotRepresentable." ) = + ErrorScaledValueNotRepresentable, + /// @deprecated Will be removed in 4.0. Use e57::ErrorReal64TooLarge. + E57_ERROR_REAL64_TOO_LARGE DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorReal64TooLarge." ) = ErrorReal64TooLarge, + /// @deprecated Will be removed in 4.0. Use e57::ErrorExpectingNumeric. + E57_ERROR_EXPECTING_NUMERIC DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorExpectingNumeric." ) = ErrorExpectingNumeric, + /// @deprecated Will be removed in 4.0. Use e57::ErrorExpectingUString. + E57_ERROR_EXPECTING_USTRING DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorExpectingUString." ) = ErrorExpectingUString, + /// @deprecated Will be removed in 4.0. Use e57::ErrorInternal. + E57_ERROR_INTERNAL DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorInternal." ) = + ErrorInternal, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadXMLFormat. + E57_ERROR_BAD_XML_FORMAT DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorBadXMLFormat." ) = + ErrorBadXMLFormat, + /// @deprecated Will be removed in 4.0. Use e57::ErrorXMLParser. + E57_ERROR_XML_PARSER DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorXMLParser." ) = + ErrorXMLParser, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadAPIArgument. + E57_ERROR_BAD_API_ARGUMENT DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorBadAPIArgument." ) = ErrorBadAPIArgument, + /// @deprecated Will be removed in 4.0. Use e57::ErrorFileReadOnly. + E57_ERROR_FILE_IS_READ_ONLY DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorFileReadOnly." ) = ErrorFileReadOnly, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadChecksum. + E57_ERROR_BAD_CHECKSUM DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorBadChecksum." ) = + ErrorBadChecksum, + /// @deprecated Will be removed in 4.0. Use e57::ErrorOpenFailed. + E57_ERROR_OPEN_FAILED DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorOpenFailed." ) = + ErrorOpenFailed, + /// @deprecated Will be removed in 4.0. Use e57::ErrorCloseFailed. + E57_ERROR_CLOSE_FAILED DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorCloseFailed." ) = + ErrorCloseFailed, + /// @deprecated Will be removed in 4.0. Use e57::ErrorReadFailed. + E57_ERROR_READ_FAILED DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorReadFailed." ) = + ErrorReadFailed, + /// @deprecated Will be removed in 4.0. Use e57::ErrorWriteFailed. + E57_ERROR_WRITE_FAILED DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorWriteFailed." ) = + ErrorWriteFailed, + /// @deprecated Will be removed in 4.0. Use e57::ErrorSeekFailed. + E57_ERROR_LSEEK_FAILED DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorSeekFailed." ) = + ErrorSeekFailed, + /// @deprecated Will be removed in 4.0. Use e57::ErrorPathUndefined. + E57_ERROR_PATH_UNDEFINED DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorPathUndefined." ) = ErrorPathUndefined, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadBuffer. + E57_ERROR_BAD_BUFFER DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorBadBuffer." ) = + ErrorBadBuffer, + /// @deprecated Will be removed in 4.0. Use e57::ErrorNoBufferForElement. + E57_ERROR_NO_BUFFER_FOR_ELEMENT DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorNoBufferForElement." ) = ErrorNoBufferForElement, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBufferSizeMismatch. + E57_ERROR_BUFFER_SIZE_MISMATCH DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorBufferSizeMismatch." ) = ErrorBufferSizeMismatch, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBufferDuplicatePathName. + E57_ERROR_BUFFER_DUPLICATE_PATHNAME DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorBufferDuplicatePathName." ) = + ErrorBufferDuplicatePathName, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadFileSignature. + E57_ERROR_BAD_FILE_SIGNATURE DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorBadFileSignature." ) = ErrorBadFileSignature, + /// @deprecated Will be removed in 4.0. Use e57::ErrorUnknownFileVersion. + E57_ERROR_UNKNOWN_FILE_VERSION DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorUnknownFileVersion." ) = ErrorUnknownFileVersion, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadFileLength. + E57_ERROR_BAD_FILE_LENGTH DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorBadFileLength." ) = ErrorBadFileLength, + /// @deprecated Will be removed in 4.0. Use e57::ErrorXMLParserInit. + E57_ERROR_XML_PARSER_INIT DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorXMLParserInit." ) = ErrorXMLParserInit, + /// @deprecated Will be removed in 4.0. Use e57::ErrorDuplicateNamespacePrefix. + E57_ERROR_DUPLICATE_NAMESPACE_PREFIX DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorDuplicateNamespacePrefix." ) = + ErrorDuplicateNamespacePrefix, + /// @deprecated Will be removed in 4.0. Use e57::ErrorDuplicateNamespaceURI. + E57_ERROR_DUPLICATE_NAMESPACE_URI DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorDuplicateNamespaceURI." ) = ErrorDuplicateNamespaceURI, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadPrototype. + E57_ERROR_BAD_PROTOTYPE DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorBadPrototype." ) = + ErrorBadPrototype, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadCodecs. + E57_ERROR_BAD_CODECS DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorBadCodecs." ) = + ErrorBadCodecs, + /// @deprecated Will be removed in 4.0. Use e57::ErrorValueOutOfBounds. + E57_ERROR_VALUE_OUT_OF_BOUNDS DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorValueOutOfBounds." ) = ErrorValueOutOfBounds, + /// @deprecated Will be removed in 4.0. Use e57::ErrorConversionRequired. + E57_ERROR_CONVERSION_REQUIRED DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorConversionRequired." ) = ErrorConversionRequired, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadPathName. + E57_ERROR_BAD_PATH_NAME DEPRECATED_ENUM( "Will be removed in 4.0. Use ErrorBadPathName." ) = + ErrorBadPathName, + /// @deprecated Will be removed in 4.0. Use e57::ErrorNotImplemented. + E57_ERROR_NOT_IMPLEMENTED DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorNotImplemented." ) = ErrorNotImplemented, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadNodeDowncast. + E57_ERROR_BAD_NODE_DOWNCAST DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorBadNodeDowncast." ) = ErrorBadNodeDowncast, + /// @deprecated Will be removed in 4.0. Use e57::ErrorWriterNotOpen. + E57_ERROR_WRITER_NOT_OPEN DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorWriterNotOpen." ) = ErrorWriterNotOpen, + /// @deprecated Will be removed in 4.0. Use e57::ErrorReaderNotOpen. + E57_ERROR_READER_NOT_OPEN DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorReaderNotOpen." ) = ErrorReaderNotOpen, + /// @deprecated Will be removed in 4.0. Use e57::ErrorNodeUnattached. + E57_ERROR_NODE_UNATTACHED DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorNodeUnattached." ) = ErrorNodeUnattached, + /// @deprecated Will be removed in 4.0. Use e57::ErrorAlreadyHasParent. + E57_ERROR_ALREADY_HAS_PARENT DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorAlreadyHasParent." ) = ErrorAlreadyHasParent, + /// @deprecated Will be removed in 4.0. Use e57::ErrorDifferentDestImageFile. + E57_ERROR_DIFFERENT_DEST_IMAGEFILE DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorDifferentDestImageFile." ) = ErrorDifferentDestImageFile, + /// @deprecated Will be removed in 4.0. Use e57::ErrorImageFileNotOpen. + E57_ERROR_IMAGEFILE_NOT_OPEN DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorImageFileNotOpen." ) = ErrorImageFileNotOpen, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBuffersNotCompatible. + E57_ERROR_BUFFERS_NOT_COMPATIBLE DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorBuffersNotCompatible." ) = ErrorBuffersNotCompatible, + /// @deprecated Will be removed in 4.0. Use e57::ErrorTooManyWriters. + E57_ERROR_TOO_MANY_WRITERS DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorTooManyWriters." ) = ErrorTooManyWriters, + /// @deprecated Will be removed in 4.0. Use e57::ErrorTooManyReaders. + E57_ERROR_TOO_MANY_READERS DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorTooManyReaders." ) = ErrorTooManyReaders, + /// @deprecated Will be removed in 4.0. Use e57::ErrorBadConfiguration. + E57_ERROR_BAD_CONFIGURATION DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorBadConfiguration." ) = ErrorBadConfiguration, + /// @deprecated Will be removed in 4.0. Use e57::ErrorInvarianceViolation. + E57_ERROR_INVARIANCE_VIOLATION DEPRECATED_ENUM( + "Will be removed in 4.0. Use ErrorInvarianceViolation." ) = ErrorInvarianceViolation, }; - class E57_DLL E57Exception : public std::exception + namespace Utilities + { + E57_DLL std::string errorCodeToString( ErrorCode ecode ) noexcept; + } + + class E57Exception : public std::exception { public: + const char *what() const noexcept override + { + return "E57 exception"; + } + void report( const char *reportingFileName = nullptr, int reportingLineNumber = 0, - const char *reportingFunctionName = nullptr, std::ostream &os = std::cout ) const; - ErrorCode errorCode() const; - std::string context() const; - const char *what() const noexcept override; + const char *reportingFunctionName = nullptr, + std::ostream &os = std::cout ) const noexcept + { + os << "**** Got an e57 exception: " << errorStr() << std::endl; + +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT + os << " Debug info: " << std::endl; + os << " context: " << context_ << std::endl; + os << " sourceFunctionName: " << sourceFunctionName_ << std::endl; + if ( reportingFunctionName != nullptr ) + { + os << " reportingFunctionName: " << reportingFunctionName << std::endl; + } + + /*** Add a line in error message that a smart editor (gnu emacs) can + * interpret as a link to the source code: */ + os << sourceFileName_ << "(" << sourceLineNumber_ << ") : error C" << errorCode_ + << ": <--- occurred on" << std::endl; + if ( reportingFileName != nullptr ) + { + os << reportingFileName << "(" << reportingLineNumber + << ") : error C0: <--- reported on" << std::endl; + } +#else + UNUSED( reportingFileName ); + UNUSED( reportingLineNumber ); + UNUSED( reportingFunctionName ); +#endif + } + + ErrorCode errorCode() const noexcept + { + return errorCode_; + } + + std::string errorStr() const noexcept + { + return Utilities::errorCodeToString( errorCode_ ); + } + + std::string context() const noexcept + { + return context_; + } // For debugging purposes: - const char *sourceFileName() const; - const char *sourceFunctionName() const; - int sourceLineNumber() const; + const char *sourceFileName() const noexcept + { + return sourceFileName_.c_str(); + } + + const char *sourceFunctionName() const noexcept + { + return sourceFunctionName_; + } - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. + int sourceLineNumber() const noexcept + { + return sourceLineNumber_; + } + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. E57Exception() = delete; - E57Exception( ErrorCode ecode, const std::string &context, const std::string &srcFileName = nullptr, - int srcLineNumber = 0, const char *srcFunctionName = nullptr ); - ~E57Exception() noexcept override = default; + E57Exception( ErrorCode ecode, std::string context, const char *srcFileName = nullptr, + int srcLineNumber = 0, const char *srcFunctionName = nullptr ) : + errorCode_( ecode ), + context_( std::move( context ) ), sourceFileName_( srcFileName ), + sourceFunctionName_( srcFunctionName ), sourceLineNumber_( srcLineNumber ) + { + } + /// @endcond - protected: + private: + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. ErrorCode errorCode_; std::string context_; std::string sourceFileName_; const char *sourceFunctionName_; int sourceLineNumber_; - //! \endcond + /// @endcond }; - - namespace Utilities - { - // Get latest version of ASTM standard supported, and library id string - E57_DLL void getVersions( int &astmMajor, int &astmMinor, std::string &libraryId ); - - E57_DLL std::string errorCodeToString( ErrorCode ecode ); - } } diff --git a/src/3rdParty/libE57Format/include/E57Format.h b/src/3rdParty/libE57Format/include/E57Format.h index a62291053444c..8123bf4b4f93d 100644 --- a/src/3rdParty/libE57Format/include/E57Format.h +++ b/src/3rdParty/libE57Format/include/E57Format.h @@ -1,697 +1,788 @@ -/* - * E57Format.h - public header of E57 API for reading/writing .e57 files. - * - * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) - * Modified work Copyright 2018 - 2020 Andy Maloney - * - * Permission is hereby granted, free of charge, to any person or organization - * obtaining a copy of the software and accompanying documentation covered by - * this license (the "Software") to use, reproduce, display, distribute, - * execute, and transmit the Software, and to prepare derivative works of the - * Software, and to permit third-parties to whom the Software is furnished to - * do so, all subject to the following: - * - * The copyright notices in the Software and this entire statement, including - * the above license grant, this restriction and the following disclaimer, - * must be included in all copies of the Software, in whole or in part, and - * all derivative works of the Software, unless such copies or derivative - * works are solely in the form of machine-executable object code generated by - * a source language processor. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT - * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE - * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - */ - -#pragma once - -//! @file E57Format.h header file for the E57 API - -#include -#include -#include -#include - -#include "E57Exception.h" - -namespace e57 -{ - using std::int16_t; - using std::int32_t; - using std::int64_t; - using std::int8_t; - using std::uint16_t; - using std::uint32_t; - using std::uint64_t; - using std::uint8_t; - - // Shorthand for unicode string - //! @brief UTF-8 encodeded Unicode string - using ustring = std::string; - - //! @brief Identifiers for types of E57 elements - enum NodeType - { - E57_STRUCTURE = 1, //!< StructureNode class - E57_VECTOR = 2, //!< VectorNode class - E57_COMPRESSED_VECTOR = 3, //!< CompressedVectorNode class - E57_INTEGER = 4, //!< IntegerNode class - E57_SCALED_INTEGER = 5, //!< ScaledIntegerNode class - E57_FLOAT = 6, //!< FloatNode class - E57_STRING = 7, //!< StringNode class - E57_BLOB = 8 //!< BlobNode class - }; - - //! @brief The IEEE floating point number precisions supported - enum FloatPrecision - { - E57_SINGLE = 1, //!< 32 bit IEEE floating point number format - E57_DOUBLE = 2 //!< 64 bit IEEE floating point number format - }; - - //! @brief Identifies the representations of memory elements API can transfer - //! data to/from - enum MemoryRepresentation - { - E57_INT8 = 1, //!< 8 bit signed integer - E57_UINT8 = 2, //!< 8 bit unsigned integer - E57_INT16 = 3, //!< 16 bit signed integer - E57_UINT16 = 4, //!< 16 bit unsigned integer - E57_INT32 = 5, //!< 32 bit signed integer - E57_UINT32 = 6, //!< 32 bit unsigned integer - E57_INT64 = 7, //!< 64 bit signed integer - E57_BOOL = 8, //!< C++ boolean type - E57_REAL32 = 9, //!< C++ float type - E57_REAL64 = 10, //!< C++ double type - E57_USTRING = 11 //!< Unicode UTF-8 std::string - }; - - //! @brief Specifies the percentage of checksums which are verified when reading - //! an ImageFile (0-100%). - using ReadChecksumPolicy = int; - - //! Do not verify the checksums. (fast) - constexpr ReadChecksumPolicy CHECKSUM_POLICY_NONE = 0; - //! Only verify 25% of the checksums. The last block is always verified. - constexpr ReadChecksumPolicy CHECKSUM_POLICY_SPARSE = 25; - //! Only verify 50% of the checksums. The last block is always verified. - constexpr ReadChecksumPolicy CHECKSUM_POLICY_HALF = 50; - //! Verify all checksums. This is the default. (slow) - constexpr ReadChecksumPolicy CHECKSUM_POLICY_ALL = 100; - - //! @brief The URI of ASTM E57 v1.0 standard XML namespace - //! Note that even though this URI does not point to a valid document, the standard (section 8.4.2.3) - //! says that this is the required namespace. - constexpr char E57_V1_0_URI[] = "http://www.astm.org/COMMIT/E57/2010-e57-v1.0"; - - //! @cond documentNonPublic The following aren't documented - // Minimum and maximum values for integers - constexpr int8_t E57_INT8_MIN = -128; - constexpr int8_t E57_INT8_MAX = 127; - constexpr int16_t E57_INT16_MIN = -32768; - constexpr int16_t E57_INT16_MAX = 32767; - constexpr int32_t E57_INT32_MIN = -2147483647 - 1; - constexpr int32_t E57_INT32_MAX = 2147483647; - constexpr int64_t E57_INT64_MIN = -9223372036854775807LL - 1; - constexpr int64_t E57_INT64_MAX = 9223372036854775807LL; - constexpr uint8_t E57_UINT8_MIN = 0U; - constexpr uint8_t E57_UINT8_MAX = 0xffU; /* 255U */ - constexpr uint16_t E57_UINT16_MIN = 0U; - constexpr uint16_t E57_UINT16_MAX = 0xffffU; /* 65535U */ - constexpr uint32_t E57_UINT32_MIN = 0U; - constexpr uint32_t E57_UINT32_MAX = 0xffffffffU; /* 4294967295U */ - constexpr uint64_t E57_UINT64_MIN = 0ULL; - constexpr uint64_t E57_UINT64_MAX = 0xffffffffffffffffULL; /* 18446744073709551615ULL */ - - constexpr float E57_FLOAT_MIN = -FLT_MAX; - constexpr float E57_FLOAT_MAX = FLT_MAX; - constexpr double E57_DOUBLE_MIN = -DBL_MAX; - constexpr double E57_DOUBLE_MAX = DBL_MAX; -//! @endcond - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -// Internal implementation files should include E57FormatImpl.h first which -// defines symbol E57_INTERNAL_IMPLEMENTATION_ENABLE. Normal API users should -// not define this symbol. Basically the internal version allows access to the -// pointer to the implementation (impl_) -#ifdef E57_INTERNAL_IMPLEMENTATION_ENABLE -#define E57_OBJECT_IMPLEMENTATION( T ) \ -public: \ - std::shared_ptr impl() const \ - { \ - return ( impl_ ); \ - } \ - \ -protected: \ - std::shared_ptr impl_; -#else -#define E57_OBJECT_IMPLEMENTATION( T ) \ -protected: \ - std::shared_ptr impl_; -#endif - //! @endcond - - class BlobNode; - class BlobNodeImpl; - class CompressedVectorNode; - class CompressedVectorNodeImpl; - class CompressedVectorReader; - class CompressedVectorReaderImpl; - class CompressedVectorWriter; - class CompressedVectorWriterImpl; - class FloatNode; - class FloatNodeImpl; - class ImageFile; - class ImageFileImpl; - class IntegerNode; - class IntegerNodeImpl; - class Node; - class NodeImpl; - class ScaledIntegerNode; - class ScaledIntegerNodeImpl; - class SourceDestBuffer; - class SourceDestBufferImpl; - class StringNode; - class StringNodeImpl; - class StructureNode; - class StructureNodeImpl; - class VectorNode; - class VectorNodeImpl; - - class E57_DLL Node - { - public: - Node() = delete; - - NodeType type() const; - bool isRoot() const; - Node parent() const; - ustring pathName() const; - ustring elementName() const; - ImageFile destImageFile() const; - bool isAttached() const; - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true, bool doDowncast = true ); - bool operator==( Node n2 ) const; - bool operator!=( Node n2 ) const; - -//! \cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -#ifdef E57_INTERNAL_IMPLEMENTATION_ENABLE - explicit Node( std::shared_ptr ); // internal use only -#endif - - private: - friend class NodeImpl; - - E57_OBJECT_IMPLEMENTATION( Node ) // Internal implementation details, not - // part of API, must be last in object - //! \endcond - }; - - class E57_DLL StructureNode - { - public: - StructureNode() = delete; - StructureNode( ImageFile destImageFile ); - - int64_t childCount() const; - bool isDefined( const ustring &pathName ) const; - Node get( int64_t index ) const; - Node get( const ustring &pathName ) const; - void set( const ustring &pathName, const Node &n ); - - // Up/Down cast conversion - operator Node() const; - explicit StructureNode( const Node &n ); - - // Common generic Node functions - bool isRoot() const; - Node parent() const; - ustring pathName() const; - ustring elementName() const; - ImageFile destImageFile() const; - bool isAttached() const; - - // Diagnostic functions: - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true, bool doUpcast = true ); - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - friend class ImageFile; - - StructureNode( std::shared_ptr ni ); // internal use only - StructureNode( std::weak_ptr fileParent ); // internal use only - - E57_OBJECT_IMPLEMENTATION( StructureNode ) // Internal implementation details, not part of API, must - // be last in object - //! \endcond - }; - - class E57_DLL VectorNode - { - public: - VectorNode() = delete; - explicit VectorNode( ImageFile destImageFile, bool allowHeteroChildren = false ); - - bool allowHeteroChildren() const; - - int64_t childCount() const; - bool isDefined( const ustring &pathName ) const; - Node get( int64_t index ) const; - Node get( const ustring &pathName ) const; - void append( const Node &n ); - - // Up/Down cast conversion - operator Node() const; - explicit VectorNode( const Node &n ); - - // Common generic Node functions - bool isRoot() const; - Node parent() const; - ustring pathName() const; - ustring elementName() const; - ImageFile destImageFile() const; - bool isAttached() const; - - // Diagnostic functions: - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true, bool doUpcast = true ); - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - friend class CompressedVectorNode; - - VectorNode( std::shared_ptr ni ); // internal use only - - E57_OBJECT_IMPLEMENTATION( VectorNode ) // Internal implementation details, not part of API, must be - // last in object - //! \endcond - }; - - class E57_DLL SourceDestBuffer - { - public: - SourceDestBuffer() = delete; - SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, int8_t *b, const size_t capacity, - bool doConversion = false, bool doScaling = false, size_t stride = sizeof( int8_t ) ); - SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, uint8_t *b, const size_t capacity, - bool doConversion = false, bool doScaling = false, size_t stride = sizeof( uint8_t ) ); - SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, int16_t *b, const size_t capacity, - bool doConversion = false, bool doScaling = false, size_t stride = sizeof( int16_t ) ); - SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, uint16_t *b, const size_t capacity, - bool doConversion = false, bool doScaling = false, size_t stride = sizeof( uint16_t ) ); - SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, int32_t *b, const size_t capacity, - bool doConversion = false, bool doScaling = false, size_t stride = sizeof( int32_t ) ); - SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, uint32_t *b, const size_t capacity, - bool doConversion = false, bool doScaling = false, size_t stride = sizeof( uint32_t ) ); - SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, int64_t *b, const size_t capacity, - bool doConversion = false, bool doScaling = false, size_t stride = sizeof( int64_t ) ); - SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, bool *b, const size_t capacity, - bool doConversion = false, bool doScaling = false, size_t stride = sizeof( bool ) ); - SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, float *b, const size_t capacity, - bool doConversion = false, bool doScaling = false, size_t stride = sizeof( float ) ); - SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, double *b, const size_t capacity, - bool doConversion = false, bool doScaling = false, size_t stride = sizeof( double ) ); - SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, std::vector *b ); - - ustring pathName() const; - enum MemoryRepresentation memoryRepresentation() const; - size_t capacity() const; - bool doConversion() const; - bool doScaling() const; - size_t stride() const; - - // Diagnostic functions: - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true ) const; - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - E57_OBJECT_IMPLEMENTATION( SourceDestBuffer ) // Internal implementation details, not part of - // API, must be last in object - //! \endcond - }; - - class E57_DLL CompressedVectorReader - { - public: - CompressedVectorReader() = delete; - - unsigned read(); - unsigned read( std::vector &dbufs ); - void seek( int64_t recordNumber ); // !!! not implemented yet - void close(); - bool isOpen(); - CompressedVectorNode compressedVectorNode() const; - - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true ); - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - friend class CompressedVectorNode; - - CompressedVectorReader( std::shared_ptr ni ); - - E57_OBJECT_IMPLEMENTATION( CompressedVectorReader ) // Internal implementation details, not - // part of API, must be last in object - //! \endcond - }; - - class E57_DLL CompressedVectorWriter - { - public: - CompressedVectorWriter() = delete; - - void write( const size_t recordCount ); - void write( std::vector &sbufs, const size_t recordCount ); - void close(); - bool isOpen(); - CompressedVectorNode compressedVectorNode() const; - - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true ); - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - friend class CompressedVectorNode; - - CompressedVectorWriter( std::shared_ptr ni ); - - E57_OBJECT_IMPLEMENTATION( CompressedVectorWriter ) // Internal implementation details, not - // part of API, must be last in object - //! \endcond - }; - - class E57_DLL CompressedVectorNode - { - public: - CompressedVectorNode() = delete; - explicit CompressedVectorNode( ImageFile destImageFile, const Node &prototype, const VectorNode &codecs ); - - int64_t childCount() const; - Node prototype() const; - VectorNode codecs() const; - - // Iterators - CompressedVectorWriter writer( std::vector &sbufs ); - CompressedVectorReader reader( const std::vector &dbufs ); - - // Up/Down cast conversion - operator Node() const; - explicit CompressedVectorNode( const Node &n ); - - // Common generic Node functions - bool isRoot() const; - Node parent() const; - ustring pathName() const; - ustring elementName() const; - ImageFile destImageFile() const; - bool isAttached() const; - - // Diagnostic functions: - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true, bool doUpcast = true ); - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - friend class CompressedVectorReader; - friend class CompressedVectorWriter; - friend class E57XmlParser; - - CompressedVectorNode( std::shared_ptr ni ); // internal use only - - E57_OBJECT_IMPLEMENTATION( CompressedVectorNode ) // Internal implementation details, not part - // of API, must be last in object - //! \endcond - }; - - class E57_DLL IntegerNode - { - public: - IntegerNode() = delete; - explicit IntegerNode( ImageFile destImageFile, int64_t value = 0, int64_t minimum = E57_INT64_MIN, - int64_t maximum = E57_INT64_MAX ); - - int64_t value() const; - int64_t minimum() const; - int64_t maximum() const; - - // Up/Down cast conversion - operator Node() const; - explicit IntegerNode( const Node &n ); - - // Common generic Node functions - bool isRoot() const; - Node parent() const; - ustring pathName() const; - ustring elementName() const; - ImageFile destImageFile() const; - bool isAttached() const; - - // Diagnostic functions: - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true, bool doUpcast = true ); - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - IntegerNode( std::shared_ptr ni ); // internal use only - - E57_OBJECT_IMPLEMENTATION( IntegerNode ) // Internal implementation details, not part of API, must be - // last in object - //! \endcond - }; - - class E57_DLL ScaledIntegerNode - { - public: - ScaledIntegerNode() = delete; - explicit ScaledIntegerNode( ImageFile destImageFile, int64_t rawValue, int64_t minimum, int64_t maximum, - double scale = 1.0, double offset = 0.0 ); - explicit ScaledIntegerNode( ImageFile destImageFile, int rawValue, int64_t minimum, int64_t maximum, - double scale = 1.0, double offset = 0.0 ); - explicit ScaledIntegerNode( ImageFile destImageFile, int rawValue, int minimum, int maximum, double scale = 1.0, - double offset = 0.0 ); - explicit ScaledIntegerNode( ImageFile destImageFile, double scaledValue, double scaledMinimum, - double scaledMaximum, double scale = 1.0, double offset = 0.0 ); - - int64_t rawValue() const; - double scaledValue() const; - int64_t minimum() const; - double scaledMinimum() const; - int64_t maximum() const; - double scaledMaximum() const; - double scale() const; - double offset() const; - - // Up/Down cast conversion - operator Node() const; - explicit ScaledIntegerNode( const Node &n ); - - // Common generic Node functions - bool isRoot() const; - Node parent() const; - ustring pathName() const; - ustring elementName() const; - ImageFile destImageFile() const; - bool isAttached() const; - - // Diagnostic functions: - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true, bool doUpcast = true ); - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - ScaledIntegerNode( std::shared_ptr ni ); // internal use only - - E57_OBJECT_IMPLEMENTATION( ScaledIntegerNode ) // Internal implementation details, not part of - // API, must be last in object - //! \endcond - }; - - class E57_DLL FloatNode - { - public: - FloatNode() = delete; - explicit FloatNode( ImageFile destImageFile, double value = 0.0, FloatPrecision precision = E57_DOUBLE, - double minimum = E57_DOUBLE_MIN, double maximum = E57_DOUBLE_MAX ); - - double value() const; - FloatPrecision precision() const; - double minimum() const; - double maximum() const; - - // Up/Down cast conversion - operator Node() const; - explicit FloatNode( const Node &n ); - - // Common generic Node functions - bool isRoot() const; - Node parent() const; - ustring pathName() const; - ustring elementName() const; - ImageFile destImageFile() const; - bool isAttached() const; - - // Diagnostic functions: - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true, bool doUpcast = true ); - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - FloatNode( std::shared_ptr ni ); // internal use only - - E57_OBJECT_IMPLEMENTATION( FloatNode ) // Internal implementation details, not part of API, must be - // last in object - //! \endcond - }; - - class E57_DLL StringNode - { - public: - StringNode() = delete; - explicit StringNode( ImageFile destImageFile, const ustring &value = "" ); - - ustring value() const; - - // Up/Down cast conversion - operator Node() const; - explicit StringNode( const Node &n ); - - // Common generic Node functions - bool isRoot() const; - Node parent() const; - ustring pathName() const; - ustring elementName() const; - ImageFile destImageFile() const; - bool isAttached() const; - - // Diagnostic functions: - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true, bool doUpcast = true ); - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - friend class StringNodeImpl; - StringNode( std::shared_ptr ni ); // internal use only - - E57_OBJECT_IMPLEMENTATION( StringNode ) // Internal implementation details, not part of API, must be - // last in object - //! \endcond - }; - - class E57_DLL BlobNode - { - public: - BlobNode() = delete; - explicit BlobNode( ImageFile destImageFile, int64_t byteCount ); - - int64_t byteCount() const; - void read( uint8_t *buf, int64_t start, size_t count ); - void write( uint8_t *buf, int64_t start, size_t count ); - - // Up/Down cast conversion - operator Node() const; - explicit BlobNode( const Node &n ); - - // Common generic Node functions - bool isRoot() const; - Node parent() const; - ustring pathName() const; - ustring elementName() const; - ImageFile destImageFile() const; - bool isAttached() const; - - // Diagnostic functions: - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true, bool doUpcast = true ); - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - friend class E57XmlParser; - - BlobNode( std::shared_ptr ni ); // internal use only - - // Internal use only, create blob already in a file - BlobNode( ImageFile destImageFile, int64_t fileOffset, int64_t length ); - - E57_OBJECT_IMPLEMENTATION( BlobNode ) // Internal implementation details, not - // part of API, must be last in object - //! \endcond - }; - - class E57_DLL ImageFile - { - public: - ImageFile() = delete; - ImageFile( const ustring &fname, const ustring &mode, ReadChecksumPolicy checksumPolicy = CHECKSUM_POLICY_ALL ); - ImageFile( const char *input, const uint64_t size, ReadChecksumPolicy checksumPolicy = CHECKSUM_POLICY_ALL ); - - StructureNode root() const; - void close(); - void cancel(); - bool isOpen() const; - bool isWritable() const; - ustring fileName() const; - int writerCount() const; - int readerCount() const; - - // Manipulate registered extensions in the file - void extensionsAdd( const ustring &prefix, const ustring &uri ); - bool extensionsLookupPrefix( const ustring &prefix, ustring &uri ) const; - bool extensionsLookupUri( const ustring &uri, ustring &prefix ) const; - size_t extensionsCount() const; - ustring extensionsPrefix( const size_t index ) const; - ustring extensionsUri( const size_t index ) const; - - // Field name functions: - bool isElementNameExtended( const ustring &elementName ) const; - void elementNameParse( const ustring &elementName, ustring &prefix, ustring &localPart ) const; - - // Diagnostic functions: - void dump( int indent = 0, std::ostream &os = std::cout ) const; - void checkInvariant( bool doRecurse = true ) const; - bool operator==( ImageFile imf2 ) const; - bool operator!=( ImageFile imf2 ) const; - - //! \cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - private: - ImageFile( double ); // Give a second dummy constructor, better error msg - // for: ImageFile(0) - - friend class Node; - friend class StructureNode; - friend class VectorNode; - friend class CompressedVectorNode; - friend class IntegerNode; - friend class ScaledIntegerNode; - friend class FloatNode; - friend class StringNode; - friend class BlobNode; - - ImageFile( std::shared_ptr imfi ); // internal use only - - E57_OBJECT_IMPLEMENTATION( ImageFile ) // Internal implementation details, not part of API, must be - // last in object - //! \endcond - }; -} +/* + * E57Format.h - public header of E57 API for reading/writing .e57 files. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#pragma once + +/// @file E57Format.h Header file for the E57 API. + +#include +#include +#include +#include + +#include "E57Exception.h" + +namespace e57 +{ + using std::int16_t; + using std::int32_t; + using std::int64_t; + using std::int8_t; + using std::uint16_t; + using std::uint32_t; + using std::uint64_t; + using std::uint8_t; + + // Shorthand for unicode string + /// @brief UTF-8 encoded Unicode string + using ustring = std::string; + + /// @brief Identifiers for types of E57 elements + enum NodeType + { + TypeStructure = 1, ///< StructureNode class + TypeVector = 2, ///< VectorNode class + TypeCompressedVector = 3, ///< CompressedVectorNode class + TypeInteger = 4, ///< IntegerNode class + TypeScaledInteger = 5, ///< ScaledIntegerNode class + TypeFloat = 6, ///< FloatNode class + TypeString = 7, ///< StringNode class + TypeBlob = 8, ///< BlobNode class + + /// @deprecated Will be removed in 4.0. Use e57::TypeStructure. + E57_STRUCTURE DEPRECATED_ENUM( "Will be removed in 4.0. Use TypeStructure." ) = TypeStructure, + /// @deprecated Will be removed in 4.0. Use e57::TypeVector. + E57_VECTOR DEPRECATED_ENUM( "Will be removed in 4.0. Use TypeVector." ) = TypeVector, + /// @deprecated Will be removed in 4.0. Use e57::TypeCompressedVector. + E57_COMPRESSED_VECTOR DEPRECATED_ENUM( "Will be removed in 4.0. Use TypeCompressedVector." ) = + TypeCompressedVector, + /// @deprecated Will be removed in 4.0. Use e57::TypeInteger. + E57_INTEGER DEPRECATED_ENUM( "Will be removed in 4.0. Use TypeInteger." ) = TypeInteger, + /// @deprecated Will be removed in 4.0. Use e57::TypeScaledInteger. + E57_SCALED_INTEGER DEPRECATED_ENUM( "Will be removed in 4.0. Use TypeScaledInteger." ) = + TypeScaledInteger, + /// @deprecated Will be removed in 4.0. Use e57::TypeFloat. + E57_FLOAT DEPRECATED_ENUM( "Will be removed in 4.0. Use TypeFloat." ) = TypeFloat, + /// @deprecated Will be removed in 4.0. Use e57::TypeString. + E57_STRING DEPRECATED_ENUM( "Will be removed in 4.0. Use TypeString." ) = TypeString, + /// @deprecated Will be removed in 4.0. Use e57::TypeBlob. + E57_BLOB DEPRECATED_ENUM( "Will be removed in 4.0. Use TypeBlob." ) = TypeBlob + }; + + /// @brief The IEEE floating point number precisions supported + enum FloatPrecision + { + PrecisionSingle = 1, ///< 32 bit IEEE floating point number format + PrecisionDouble = 2, ///< 64 bit IEEE floating point number format + + /// @deprecated Will be removed in 4.0. Use e57::PrecisionSingle. + E57_SINGLE DEPRECATED_ENUM( "Will be removed in 4.0. Use PrecisionSingle." ) = + PrecisionSingle, + /// @deprecated Will be removed in 4.0. Use e57::PrecisionDouble. + E57_DOUBLE DEPRECATED_ENUM( "Will be removed in 4.0. Use PrecisionDouble." ) = PrecisionDouble + }; + + /// @brief Identifies the representations of memory elements API can transfer data to/from + enum MemoryRepresentation + { + Int8 = 1, ///< 8 bit signed integer + UInt8 = 2, ///< 8 bit unsigned integer + Int16 = 3, ///< 16 bit signed integer + UInt16 = 4, ///< 16 bit unsigned integer + Int32 = 5, ///< 32 bit signed integer + UInt32 = 6, ///< 32 bit unsigned integer + Int64 = 7, ///< 64 bit signed integer + Bool = 8, ///< C++ boolean type + Real32 = 9, ///< C++ float type + Real64 = 10, ///< C++ double type + UString = 11, ///< Unicode UTF-8 std::string + + /// @deprecated Will be removed in 4.0. Use e57::Int8. + E57_INT8 DEPRECATED_ENUM( "Will be removed in 4.0. Use Int8." ) = Int8, + /// @deprecated Will be removed in 4.0. Use e57::UInt8. + E57_UINT8 DEPRECATED_ENUM( "Will be removed in 4.0. Use UInt8." ) = UInt8, + /// @deprecated Will be removed in 4.0. Use e57::Int16. + E57_INT16 DEPRECATED_ENUM( "Will be removed in 4.0. Use Int16." ) = Int16, + /// @deprecated Will be removed in 4.0. Use e57::UInt16. + E57_UINT16 DEPRECATED_ENUM( "Will be removed in 4.0. Use UInt16." ) = UInt16, + /// @deprecated Will be removed in 4.0. Use e57::Int32. + E57_INT32 DEPRECATED_ENUM( "Will be removed in 4.0. Use Int32." ) = Int32, + /// @deprecated Will be removed in 4.0. Use e57::UInt32. + E57_UINT32 DEPRECATED_ENUM( "Will be removed in 4.0. Use UInt32." ) = UInt32, + /// @deprecated Will be removed in 4.0. Use e57::Int64. + E57_INT64 DEPRECATED_ENUM( "Will be removed in 4.0. Use Int64." ) = Int64, + /// @deprecated Will be removed in 4.0. Use e57::Bool. + E57_BOOL DEPRECATED_ENUM( "Will be removed in 4.0. Use Bool." ) = Bool, + /// @deprecated Will be removed in 4.0. Use e57::Real32. + E57_REAL32 DEPRECATED_ENUM( "Will be removed in 4.0. Use Real32." ) = Real32, + /// @deprecated Will be removed in 4.0. Use e57::Real64. + E57_REAL64 DEPRECATED_ENUM( "Will be removed in 4.0. Use Real64." ) = Real64, + /// @deprecated Will be removed in 4.0. Use e57::UString. + E57_USTRING DEPRECATED_ENUM( "Will be removed in 4.0. Use UString." ) = UString + }; + + /// @brief Default checksum policies for e57::ReadChecksumPolicy + /// @details These are some convenient default checksum policies, though you can use any value + /// you want (0-100). + enum ChecksumPolicy + { + ChecksumNone = 0, ///< Do not verify the checksums. (fast) + ChecksumSparse = 25, ///< Only verify 25% of the checksums. The last block is always verified. + ChecksumHalf = 50, ///< Only verify 50% of the checksums. The last block is always verified. + ChecksumAll = 100 ///< Verify all checksums. This is the default. (slow) + }; + + /// @brief Specifies the percentage of checksums which are verified when reading an ImageFile + /// (0-100%). + /// @see e57::ChecksumPolicy + using ReadChecksumPolicy = int; + + /// @name Deprecated Checksum Policies + /// These have been replaced by the enum e57::ChecksumPolicy. + ///@{ + + /// @deprecated Will be removed in 4.0. Use ChecksumPolicy::ChecksumNone. + [[deprecated( + "Will be removed in 4.0. Use ChecksumPolicy::ChecksumNone." )]] // TODO Remove in 4.0 + constexpr ReadChecksumPolicy CHECKSUM_POLICY_NONE = ChecksumNone; + + /// @deprecated Will be removed in 4.0. Use ChecksumPolicy::ChecksumSparse. + [[deprecated( + "Will be removed in 4.0. Use ChecksumPolicy::ChecksumSparse." )]] // TODO Remove in 4.0 + constexpr ReadChecksumPolicy CHECKSUM_POLICY_SPARSE = ChecksumSparse; + + /// @deprecated Will be removed in 4.0. Use ChecksumPolicy::ChecksumHalf. + [[deprecated( + "Will be removed in 4.0. Use ChecksumPolicy::ChecksumHalf." )]] // TODO Remove in 4.0 + constexpr ReadChecksumPolicy CHECKSUM_POLICY_HALF = ChecksumHalf; + + /// @deprecated Will be removed in 4.0. Use ChecksumPolicy::ChecksumAll. + [[deprecated( + "Will be removed in 4.0. Use ChecksumPolicy::ChecksumAll." )]] // TODO Remove in 4.0 + constexpr ReadChecksumPolicy CHECKSUM_POLICY_ALL = ChecksumAll; + + ///@} + + /// @brief The URI of ASTM E57 v1.0 standard XML namespace + /// @note Even though this URI does not point to a valid document, the standard (section 8.4.2.3) + /// says that this is the required namespace. + constexpr char VERSION_1_0_URI[] = "http://www.astm.org/COMMIT/E57/2010-e57-v1.0"; + + /// @deprecated Will be removed in 4.0. Use e57::VERSION_1_0_URI. + [[deprecated( "Will be removed in 4.0. Use e57::VERSION_1_0_URI." )]] // TODO Remove in 4.0 + constexpr auto E57_V1_0_URI = VERSION_1_0_URI; + + /// @cond documentNonPublic The following aren't documented + // Minimum and maximum values for integers + constexpr uint8_t UINT8_MIN = 0U; + constexpr uint16_t UINT16_MIN = 0U; + constexpr uint32_t UINT32_MIN = 0U; + constexpr uint64_t UINT64_MIN = 0ULL; + + constexpr float FLOAT_MIN = -FLT_MAX; + constexpr float FLOAT_MAX = FLT_MAX; + constexpr double DOUBLE_MIN = -DBL_MAX; + constexpr double DOUBLE_MAX = DBL_MAX; + /// @endcond + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + // Internal implementation files should include Common.h first which defines symbol + // E57_INTERNAL_IMPLEMENTATION_ENABLE. Normal API users should not define this symbol. + // Basically the internal version allows access to the pointer to the implementation (impl_) +#ifdef E57_INTERNAL_IMPLEMENTATION_ENABLE +#define E57_INTERNAL_ACCESS( T ) \ +public: \ + std::shared_ptr impl() const \ + { \ + return ( impl_ ); \ + } +#else +#define E57_INTERNAL_ACCESS( T ) +#endif + /// @endcond + + class BlobNode; + class BlobNodeImpl; + class CompressedVectorNode; + class CompressedVectorNodeImpl; + class CompressedVectorReader; + class CompressedVectorReaderImpl; + class CompressedVectorWriter; + class CompressedVectorWriterImpl; + class FloatNode; + class FloatNodeImpl; + class ImageFile; + class ImageFileImpl; + class IntegerNode; + class IntegerNodeImpl; + class Node; + class NodeImpl; + class ScaledIntegerNode; + class ScaledIntegerNodeImpl; + class SourceDestBuffer; + class SourceDestBufferImpl; + class StringNode; + class StringNodeImpl; + class StructureNode; + class StructureNodeImpl; + class VectorNode; + class VectorNodeImpl; + + class E57_DLL Node + { + public: + Node() = delete; + + NodeType type() const; + bool isRoot() const; + Node parent() const; + ustring pathName() const; + ustring elementName() const; + ImageFile destImageFile() const; + bool isAttached() const; + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true, bool doDowncast = true ); + bool operator==( const Node &n2 ) const; + bool operator!=( const Node &n2 ) const; + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. +#ifdef E57_INTERNAL_IMPLEMENTATION_ENABLE + explicit Node( std::shared_ptr ); // internal use only +#endif + + private: + friend class NodeImpl; + + E57_INTERNAL_ACCESS( Node ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL StructureNode + { + public: + StructureNode() = delete; + explicit StructureNode( const ImageFile &destImageFile ); + + int64_t childCount() const; + bool isDefined( const ustring &pathName ) const; + Node get( int64_t index ) const; + Node get( const ustring &pathName ) const; + void set( const ustring &pathName, const Node &n ); + + // Up/Down cast conversion + operator Node() const; + explicit StructureNode( const Node &n ); + + // Common generic Node functions + bool isRoot() const; + Node parent() const; + ustring pathName() const; + ustring elementName() const; + ImageFile destImageFile() const; + bool isAttached() const; + + // Diagnostic functions: + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true, bool doUpcast = true ) const; + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + private: + friend class ImageFile; + + explicit StructureNode( std::shared_ptr ni ); + explicit StructureNode( std::weak_ptr fileParent ); + + E57_INTERNAL_ACCESS( StructureNode ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL VectorNode + { + public: + VectorNode() = delete; + explicit VectorNode( const ImageFile &destImageFile, bool allowHeteroChildren = false ); + + bool allowHeteroChildren() const; + + int64_t childCount() const; + bool isDefined( const ustring &pathName ) const; + Node get( int64_t index ) const; + Node get( const ustring &pathName ) const; + void append( const Node &n ); + + // Up/Down cast conversion + operator Node() const; + explicit VectorNode( const Node &n ); + + // Common generic Node functions + bool isRoot() const; + Node parent() const; + ustring pathName() const; + ustring elementName() const; + ImageFile destImageFile() const; + bool isAttached() const; + + // Diagnostic functions: + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true, bool doUpcast = true ) const; + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + private: + friend class CompressedVectorNode; + + explicit VectorNode( std::shared_ptr ni ); // internal use only + + E57_INTERNAL_ACCESS( VectorNode ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL SourceDestBuffer + { + public: + SourceDestBuffer() = delete; + SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, int8_t *b, + size_t capacity, bool doConversion = false, bool doScaling = false, + size_t stride = sizeof( int8_t ) ); + SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, uint8_t *b, + size_t capacity, bool doConversion = false, bool doScaling = false, + size_t stride = sizeof( uint8_t ) ); + SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, int16_t *b, + size_t capacity, bool doConversion = false, bool doScaling = false, + size_t stride = sizeof( int16_t ) ); + SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, uint16_t *b, + size_t capacity, bool doConversion = false, bool doScaling = false, + size_t stride = sizeof( uint16_t ) ); + SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, int32_t *b, + size_t capacity, bool doConversion = false, bool doScaling = false, + size_t stride = sizeof( int32_t ) ); + SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, uint32_t *b, + size_t capacity, bool doConversion = false, bool doScaling = false, + size_t stride = sizeof( uint32_t ) ); + SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, int64_t *b, + size_t capacity, bool doConversion = false, bool doScaling = false, + size_t stride = sizeof( int64_t ) ); + SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, bool *b, + size_t capacity, bool doConversion = false, bool doScaling = false, + size_t stride = sizeof( bool ) ); + SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, float *b, + size_t capacity, bool doConversion = false, bool doScaling = false, + size_t stride = sizeof( float ) ); + SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, double *b, + size_t capacity, bool doConversion = false, bool doScaling = false, + size_t stride = sizeof( double ) ); + SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + std::vector *b ); + + ustring pathName() const; + enum MemoryRepresentation memoryRepresentation() const; + size_t capacity() const; + bool doConversion() const; + bool doScaling() const; + size_t stride() const; + + // Diagnostic functions: + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true ) const; + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + E57_INTERNAL_ACCESS( SourceDestBuffer ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL CompressedVectorReader + { + public: + CompressedVectorReader() = delete; + + unsigned read(); + unsigned read( std::vector &dbufs ); + void seek( int64_t recordNumber ); // !!! not implemented yet + void close(); + bool isOpen(); + CompressedVectorNode compressedVectorNode() const; + + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true ); + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + private: + friend class CompressedVectorNode; + + explicit CompressedVectorReader( std::shared_ptr ni ); + + E57_INTERNAL_ACCESS( CompressedVectorReader ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL CompressedVectorWriter + { + public: + CompressedVectorWriter() = delete; + + void write( size_t recordCount ); + void write( std::vector &sbufs, size_t recordCount ); + void close(); + bool isOpen(); + CompressedVectorNode compressedVectorNode() const; + + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true ); + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + private: + friend class CompressedVectorNode; + + explicit CompressedVectorWriter( std::shared_ptr ni ); + + E57_INTERNAL_ACCESS( CompressedVectorWriter ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL CompressedVectorNode + { + public: + CompressedVectorNode() = delete; + explicit CompressedVectorNode( const ImageFile &destImageFile, const Node &prototype, + const VectorNode &codecs ); + + int64_t childCount() const; + Node prototype() const; + VectorNode codecs() const; + + // Iterators + CompressedVectorWriter writer( std::vector &sbufs ); + CompressedVectorReader reader( const std::vector &dbufs ); + + // Up/Down cast conversion + operator Node() const; + explicit CompressedVectorNode( const Node &n ); + + // Common generic Node functions + bool isRoot() const; + Node parent() const; + ustring pathName() const; + ustring elementName() const; + ImageFile destImageFile() const; + bool isAttached() const; + + // Diagnostic functions: + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true, bool doUpcast = true ) const; + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + private: + friend class CompressedVectorReader; + friend class CompressedVectorWriter; + friend class E57XmlParser; + + CompressedVectorNode( std::shared_ptr ni ); + + E57_INTERNAL_ACCESS( CompressedVectorNode ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL IntegerNode + { + public: + IntegerNode() = delete; + explicit IntegerNode( const ImageFile &destImageFile, int64_t value = 0, + int64_t minimum = INT64_MIN, int64_t maximum = INT64_MAX ); + + int64_t value() const; + int64_t minimum() const; + int64_t maximum() const; + + // Up/Down cast conversion + operator Node() const; + explicit IntegerNode( const Node &n ); + + // Common generic Node functions + bool isRoot() const; + Node parent() const; + ustring pathName() const; + ustring elementName() const; + ImageFile destImageFile() const; + bool isAttached() const; + + // Diagnostic functions: + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true, bool doUpcast = true ) const; + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + private: + explicit IntegerNode( std::shared_ptr ni ); + + E57_INTERNAL_ACCESS( IntegerNode ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL ScaledIntegerNode + { + public: + ScaledIntegerNode() = delete; + explicit ScaledIntegerNode( const ImageFile &destImageFile, int64_t rawValue, int64_t minimum, + int64_t maximum, double scale = 1.0, double offset = 0.0 ); + explicit ScaledIntegerNode( const ImageFile &destImageFile, int rawValue, int64_t minimum, + int64_t maximum, double scale = 1.0, double offset = 0.0 ); + explicit ScaledIntegerNode( const ImageFile &destImageFile, int rawValue, int minimum, + int maximum, double scale = 1.0, double offset = 0.0 ); + explicit ScaledIntegerNode( const ImageFile &destImageFile, double scaledValue, + double scaledMinimum, double scaledMaximum, double scale = 1.0, + double offset = 0.0 ); + + int64_t rawValue() const; + double scaledValue() const; + int64_t minimum() const; + double scaledMinimum() const; + int64_t maximum() const; + double scaledMaximum() const; + double scale() const; + double offset() const; + + // Up/Down cast conversion + operator Node() const; + explicit ScaledIntegerNode( const Node &n ); + + // Common generic Node functions + bool isRoot() const; + Node parent() const; + ustring pathName() const; + ustring elementName() const; + ImageFile destImageFile() const; + bool isAttached() const; + + // Diagnostic functions: + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true, bool doUpcast = true ) const; + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + private: + explicit ScaledIntegerNode( std::shared_ptr ni ); + + E57_INTERNAL_ACCESS( ScaledIntegerNode ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL FloatNode + { + public: + FloatNode() = delete; + explicit FloatNode( const ImageFile &destImageFile, double value = 0.0, + FloatPrecision precision = PrecisionDouble, double minimum = DOUBLE_MIN, + double maximum = DOUBLE_MAX ); + + double value() const; + FloatPrecision precision() const; + double minimum() const; + double maximum() const; + + // Up/Down cast conversion + operator Node() const; + explicit FloatNode( const Node &n ); + + // Common generic Node functions + bool isRoot() const; + Node parent() const; + ustring pathName() const; + ustring elementName() const; + ImageFile destImageFile() const; + bool isAttached() const; + + // Diagnostic functions: + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true, bool doUpcast = true ) const; + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + private: + explicit FloatNode( std::shared_ptr ni ); + + E57_INTERNAL_ACCESS( FloatNode ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL StringNode + { + public: + StringNode() = delete; + explicit StringNode( const ImageFile &destImageFile, const ustring &value = "" ); + + ustring value() const; + + // Up/Down cast conversion + operator Node() const; + explicit StringNode( const Node &n ); + + // Common generic Node functions + bool isRoot() const; + Node parent() const; + ustring pathName() const; + ustring elementName() const; + ImageFile destImageFile() const; + bool isAttached() const; + + // Diagnostic functions: + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true, bool doUpcast = true ) const; + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + private: + friend class StringNodeImpl; + + explicit StringNode( std::shared_ptr ni ); + + E57_INTERNAL_ACCESS( StringNode ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL BlobNode + { + public: + BlobNode() = delete; + explicit BlobNode( const ImageFile &destImageFile, int64_t byteCount ); + + int64_t byteCount() const; + void read( uint8_t *buf, int64_t start, size_t count ); + void write( uint8_t *buf, int64_t start, size_t count ); + + // Up/Down cast conversion + operator Node() const; + explicit BlobNode( const Node &n ); + + // Common generic Node functions + bool isRoot() const; + Node parent() const; + ustring pathName() const; + ustring elementName() const; + ImageFile destImageFile() const; + bool isAttached() const; + + // Diagnostic functions: + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true, bool doUpcast = true ) const; + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + private: + friend class E57XmlParser; + + explicit BlobNode( std::shared_ptr ni ); + + // create blob already in a file + BlobNode( const ImageFile &destImageFile, int64_t fileOffset, int64_t length ); + + E57_INTERNAL_ACCESS( BlobNode ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; + + class E57_DLL ImageFile + { + public: + ImageFile() = delete; + ImageFile( const ustring &fname, const ustring &mode, + ReadChecksumPolicy checksumPolicy = ChecksumAll ); + ImageFile( const char *input, uint64_t size, + ReadChecksumPolicy checksumPolicy = ChecksumAll ); + + StructureNode root() const; + void close(); + void cancel(); + bool isOpen() const; + bool isWritable() const; + ustring fileName() const; + int writerCount() const; + int readerCount() const; + + // Manipulate registered extensions in the file + void extensionsAdd( const ustring &prefix, const ustring &uri ); + bool extensionsLookupPrefix( const ustring &prefix ) const; + bool extensionsLookupPrefix( const ustring &prefix, ustring &uri ) const; + bool extensionsLookupUri( const ustring &uri, ustring &prefix ) const; + size_t extensionsCount() const; + ustring extensionsPrefix( size_t index ) const; + ustring extensionsUri( size_t index ) const; + + // Field name functions: + bool isElementNameExtended( const ustring &elementName ) const; + void elementNameParse( const ustring &elementName, ustring &prefix, + ustring &localPart ) const; + + // Diagnostic functions: + void dump( int indent = 0, std::ostream &os = std::cout ) const; + void checkInvariant( bool doRecurse = true ) const; + bool operator==( const ImageFile &imf2 ) const; + bool operator!=( const ImageFile &imf2 ) const; + + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. + private: + explicit ImageFile( double ); // Dummy constructor for better error msg for: ImageFile(0) + + friend class Node; + friend class StructureNode; + friend class VectorNode; + friend class CompressedVectorNode; + friend class IntegerNode; + friend class ScaledIntegerNode; + friend class FloatNode; + friend class StringNode; + friend class BlobNode; + + explicit ImageFile( std::shared_ptr imfi ); + + E57_INTERNAL_ACCESS( ImageFile ) + + protected: + std::shared_ptr impl_; + /// @endcond + }; +} diff --git a/src/3rdParty/libE57Format/include/E57SimpleData.h b/src/3rdParty/libE57Format/include/E57SimpleData.h index 47eb35e3574ea..02608bd6daaeb 100644 --- a/src/3rdParty/libE57Format/include/E57SimpleData.h +++ b/src/3rdParty/libE57Format/include/E57SimpleData.h @@ -3,6 +3,7 @@ * * Copyright (c) 2010 Stan Coleby (scoleby@intelisum.com) * Copyright (c) 2020 PTC Inc. + * Copyright (c) 2022 Andy Maloney * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by @@ -29,152 +30,190 @@ #pragma once -//! @file E57SimpleData.h Data structures for E57 Simple API +/// @file +/// @brief Data structures for E57 Simple API #include "E57Format.h" namespace e57 { - - //! Indicates to use FloatNode instead of ScaledIntegerNode in fields that can use both. - constexpr double E57_NOT_SCALED_USE_FLOAT = 0.; - //! Indicates to use ScaledIntegerNode instead of FloatNode in fields that can use both. - constexpr double E57_NOT_SCALED_USE_INTEGER = -1.; - - //! @cond documentNonPublic The following isn't part of the API, and isn't documented. + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. class ReaderImpl; class WriterImpl; - //! @endcond + /// @endcond - //! @brief Defines a rigid body translation in Cartesian coordinates. + /// @brief Defines a rigid body translation in Cartesian coordinates. struct E57_DLL Translation { - double x{ 0. }; //!< The X coordinate of the translation (in meters) - double y{ 0. }; //!< The Y coordinate of the translation (in meters) - double z{ 0. }; //!< The Z coordinate of the translation (in meters) + /// The X coordinate of the translation (in meters) + double x = 0.0; + + /// The Y coordinate of the translation (in meters) + double y = 0.0; + + /// The Z coordinate of the translation (in meters) + double z = 0.0; bool operator==( const Translation &rhs ) const { return ( x == rhs.x ) && ( y == rhs.y ) && ( z == rhs.z ); } + bool operator!=( const Translation &rhs ) const { return !operator==( rhs ); } + /// @brief Return "no translation". + /// @returns A translation of (0.0, 0.0, 0.0). static Translation identity() { return {}; } }; - //! @brief Represents a rigid body rotation. + /// @brief Represents a rigid body rotation. struct E57_DLL Quaternion { - double w{ 0. }; //!< The real part of the quaternion. Shall be nonnegative - double x{ 0. }; //!< The i coefficient of the quaternion - double y{ 0. }; //!< The j coefficient of the quaternion - double z{ 0. }; //!< The k coefficient of the quaternion + /// The real part of the quaternion (shall be nonnegative) + double w = 1.0; + + /// The i coefficient of the quaternion + double x = 0.0; + + /// The j coefficient of the quaternion + double y = 0.0; + + /// The k coefficient of the quaternion + double z = 0.0; bool operator==( const Quaternion &rhs ) const { return ( w == rhs.w ) && ( x == rhs.x ) && ( y == rhs.y ) && ( z == rhs.z ); } + bool operator!=( const Quaternion &rhs ) const { return !operator==( rhs ); } + /// @brief Return the identity quaternion. + /// @returns A quaternion of (1.0, 0.0, 0.0, 0.0). static Quaternion identity() { - Quaternion identity; - identity.w = 1.; - return identity; + return {}; } }; - //! @brief Defines a rigid body transform in cartesian coordinates. + /// @brief Defines a rigid body transform in cartesian coordinates. struct E57_DLL RigidBodyTransform { - Quaternion rotation; //!< A unit quaternion representing the rotation, R, of the transform - Translation translation; //!< The translation point vector, t, of the transform + /// A unit quaternion representing the rotation, R, of the transform + Quaternion rotation; + + /// The translation point vector, t, of the transform + Translation translation; bool operator==( const RigidBodyTransform &rhs ) const { return ( rotation == rhs.rotation ) && ( translation == rhs.translation ); } + bool operator!=( const RigidBodyTransform &rhs ) const { return !operator==( rhs ); } + /// @brief Returns a RigidBodyTransform without rotation or translation. static RigidBodyTransform identity() { return { Quaternion::identity(), Translation::identity() }; } }; - //! @brief Specifies an axis-aligned box in local cartesian coordinates. + /// @brief Specifies an axis-aligned box in local cartesian coordinates. struct E57_DLL CartesianBounds { - double xMinimum{ -E57_DOUBLE_MAX }; //!< The minimum extent of the bounding box in the X direction - double xMaximum{ E57_DOUBLE_MAX }; //!< The maximum extent of the bounding box in the X direction - double yMinimum{ -E57_DOUBLE_MAX }; //!< The minimum extent of the bounding box in the Y direction - double yMaximum{ E57_DOUBLE_MAX }; //!< The maximum extent of the bounding box in the Y direction - double zMinimum{ -E57_DOUBLE_MAX }; //!< The minimum extent of the bounding box in the Z direction - double zMaximum{ E57_DOUBLE_MAX }; //!< The maximum extent of the bounding box in the Z direction + /// The minimum extent of the bounding box in the X direction + double xMinimum = -DOUBLE_MAX; + /// The maximum extent of the bounding box in the X direction + double xMaximum = DOUBLE_MAX; + + /// The minimum extent of the bounding box in the Y direction + double yMinimum = -DOUBLE_MAX; + /// The maximum extent of the bounding box in the Y direction + double yMaximum = DOUBLE_MAX; + + /// The minimum extent of the bounding box in the Z direction + double zMinimum = -DOUBLE_MAX; + /// The maximum extent of the bounding box in the Z direction + double zMaximum = DOUBLE_MAX; bool operator==( const CartesianBounds &rhs ) const { - return ( xMinimum == rhs.xMinimum ) && ( xMaximum == rhs.xMaximum ) && ( yMinimum == rhs.yMinimum ) && - ( yMaximum == rhs.yMaximum ) && ( zMinimum == rhs.zMinimum ) && ( zMaximum == rhs.zMaximum ); + return ( xMinimum == rhs.xMinimum ) && ( xMaximum == rhs.xMaximum ) && + ( yMinimum == rhs.yMinimum ) && ( yMaximum == rhs.yMaximum ) && + ( zMinimum == rhs.zMinimum ) && ( zMaximum == rhs.zMaximum ); } + bool operator!=( const CartesianBounds &rhs ) const { return !operator==( rhs ); } }; - //! @brief Stores the bounds of some data in spherical coordinates. + /// @brief Stores the bounds of some data in spherical coordinates. struct E57_DLL SphericalBounds { - SphericalBounds(); // constructor in the cpp to avoid exposing M_PI - double rangeMinimum; //!< The minimum extent of the bounding region in the r direction - double rangeMaximum; //!< The maximum extent of the bounding region in the r direction - double elevationMinimum; //!< The minimum extent of the bounding region from the horizontal plane - double elevationMaximum; //!< The maximum extent of the bounding region from the horizontal plane - double azimuthStart; //!< The starting azimuth angle defining the extent of the bounding region around the z axis - double azimuthEnd; //!< The ending azimuth angle defining the extent of the bounding region around the z axis + SphericalBounds(); // constructor in the cpp to avoid exposing M_PI + + /// The minimum extent of the bounding region in the r direction + double rangeMinimum; + /// The maximum extent of the bounding region in the r direction + double rangeMaximum; + + /// The minimum extent of the bounding region from the horizontal plane + double elevationMinimum; + /// The maximum extent of the bounding region from the horizontal plane + double elevationMaximum; + + ///< The starting azimuth angle defining the extent of the bounding region around the z axis + double azimuthStart; + ///< The ending azimuth angle defining the extent of the bounding region around the z axis + double azimuthEnd; bool operator==( const SphericalBounds &rhs ) const { return ( rangeMinimum == rhs.rangeMinimum ) && ( rangeMaximum == rhs.rangeMaximum ) && - ( elevationMinimum == rhs.elevationMinimum ) && ( elevationMaximum == rhs.elevationMaximum ) && + ( elevationMinimum == rhs.elevationMinimum ) && + ( elevationMaximum == rhs.elevationMaximum ) && ( azimuthStart == rhs.azimuthStart ) && ( azimuthEnd == rhs.azimuthEnd ); } + bool operator!=( const SphericalBounds &rhs ) const { return !operator==( rhs ); } }; - //! @brief Stores the minimum and maximum of rowIndex, columnIndex, and returnIndex fields for a set of points. + /// @brief Stores the minimum and maximum of rowIndex, columnIndex, and returnIndex fields for a + /// set of points. struct E57_DLL IndexBounds { - int64_t rowMinimum{ 0 }; //!< The minimum rowIndex value of any point represented by this IndexBounds object. - int64_t rowMaximum{ 0 }; //!< The maximum rowIndex value of any point represented by this IndexBounds object. - int64_t columnMinimum{ - 0 - }; //!< The minimum columnIndex value of any point represented by this IndexBounds object. - int64_t columnMaximum{ - 0 - }; //!< The maximum columnIndex value of any point represented by this IndexBounds object. - int64_t returnMinimum{ - 0 - }; //!< The minimum returnIndex value of any point represented by this IndexBounds object. - int64_t returnMaximum{ - 0 - }; //!< The maximum returnIndex value of any point represented by this IndexBounds object. + /// The minimum rowIndex value of any point represented by this IndexBounds object + int64_t rowMinimum = 0; + /// The maximum rowIndex value of any point represented by this IndexBounds object + int64_t rowMaximum = 0; + + /// The minimum columnIndex value of any point represented by this IndexBounds object + int64_t columnMinimum = 0; + /// The maximum columnIndex value of any point represented by this IndexBounds object + int64_t columnMaximum = 0; + + /// The minimum returnIndex value of any point represented by this IndexBounds object + int64_t returnMinimum = 0; + /// The maximum returnIndex value of any point represented by this IndexBounds object + int64_t returnMaximum = 0; bool operator==( const IndexBounds &rhs ) const { @@ -182,329 +221,549 @@ namespace e57 ( columnMinimum == rhs.columnMinimum ) && ( columnMaximum == rhs.columnMaximum ) && ( returnMinimum == rhs.returnMinimum ) && ( returnMaximum == rhs.returnMaximum ); } + bool operator!=( const IndexBounds &rhs ) const { return !operator==( rhs ); } }; - //! @brief Specifies the limits for the value of signal intensity that a sensor is capable of producing + /// @brief Specifies the limits for the value of signal intensity that a sensor is capable of + /// producing struct E57_DLL IntensityLimits { - double intensityMinimum{ 0. }; //!< The minimum producible intensity value. Unit is unspecified. - double intensityMaximum{ 0. }; //!< The maximum producible intensity value. Unit is unspecified. + /// The minimum producible intensity value. Unit is unspecified. + double intensityMinimum = 0.0; + /// The maximum producible intensity value. Unit is unspecified. + double intensityMaximum = 0.0; bool operator==( const IntensityLimits &rhs ) const { - return ( intensityMinimum == rhs.intensityMinimum ) && ( intensityMaximum == rhs.intensityMaximum ); + return ( intensityMinimum == rhs.intensityMinimum ) && + ( intensityMaximum == rhs.intensityMaximum ); } + bool operator!=( const IntensityLimits &rhs ) const { return !operator==( rhs ); } }; - //! @brief Specifies the limits for the value of red, green, and blue color that a sensor is capable of producing. + /// @brief Specifies the limits for the value of red, green, and blue color that a sensor is + /// capable of producing. struct E57_DLL ColorLimits { - double colorRedMinimum{ 0. }; //!< The minimum producible red color value. Unit is unspecified. - double colorRedMaximum{ 0. }; //!< The maximum producible red color value. Unit is unspecified. - double colorGreenMinimum{ 0. }; //!< The minimum producible green color value. Unit is unspecified. - double colorGreenMaximum{ 0. }; //!< The maximum producible green color value. Unit is unspecified. - double colorBlueMinimum{ 0. }; //!< The minimum producible blue color value. Unit is unspecified. - double colorBlueMaximum{ 0. }; //!< The maximum producible blue color value. Unit is unspecified. + /// The minimum producible red color value. Unit is unspecified. + double colorRedMinimum = 0.0; + /// The maximum producible red color value. Unit is unspecified. + double colorRedMaximum = 0.0; + + /// The minimum producible green color value. Unit is unspecified. + double colorGreenMinimum = 0.0; + /// The maximum producible green color value. Unit is unspecified. + double colorGreenMaximum = 0.0; + + /// The minimum producible blue color value. Unit is unspecified. + double colorBlueMinimum = 0.0; + /// The maximum producible blue color value. Unit is unspecified. + double colorBlueMaximum = 0.0; bool operator==( const ColorLimits &rhs ) const { - return ( colorRedMinimum == rhs.colorRedMinimum ) && ( colorRedMaximum == rhs.colorRedMaximum ) && - ( colorGreenMinimum == rhs.colorGreenMinimum ) && ( colorGreenMaximum == rhs.colorGreenMaximum ) && - ( colorBlueMinimum == rhs.colorBlueMinimum ) && ( colorBlueMaximum == rhs.colorBlueMaximum ); + return ( colorRedMinimum == rhs.colorRedMinimum ) && + ( colorRedMaximum == rhs.colorRedMaximum ) && + ( colorGreenMinimum == rhs.colorGreenMinimum ) && + ( colorGreenMaximum == rhs.colorGreenMaximum ) && + ( colorBlueMinimum == rhs.colorBlueMinimum ) && + ( colorBlueMaximum == rhs.colorBlueMaximum ); } + bool operator!=( const ColorLimits &rhs ) const { return !operator==( rhs ); } }; - //! @brief Encodes date and time. - //! @details The date and time is encoded using a single floating point number, stored as an E57 Float element which - //! is based on the Global Positioning - //! System (GPS) time scale. + /// @brief Encodes date and time. + /// @details The date and time is encoded using a single floating point number, stored as an E57 + /// Float element which is based on the Global Positioning System (GPS) time scale. struct E57_DLL DateTime { - double dateTimeValue{ - 0. - }; //!< The time, in seconds, since GPS time was zero. This time specification may include fractions of a second. - int32_t isAtomicClockReferenced{ - 0 - }; //!< This element should be present, and its value set to 1 if, and only if, the time stored in the - //!< dateTimeValue element is obtained from an atomic clock time source. Shall be either 0 or 1. + /// @brief The time, in seconds, since GPS time was zero. + /// @details This time specification may include fractions of a second. + double dateTimeValue = 0.0; + + /// @brief This element should be present, and its value set to 1 if, and only if, the time + /// stored in the dateTimeValue element is obtained from an atomic clock time source. + /// @details Shall be either 0 or 1. + int32_t isAtomicClockReferenced = 0; bool operator==( const DateTime &rhs ) const { - return ( dateTimeValue == rhs.dateTimeValue ) && ( isAtomicClockReferenced == rhs.isAtomicClockReferenced ); + return ( dateTimeValue == rhs.dateTimeValue ) && + ( isAtomicClockReferenced == rhs.isAtomicClockReferenced ); } + bool operator!=( const DateTime &rhs ) const { return !operator==( rhs ); } }; - //! @brief Stores the top-level information for the XML section of the file. + /// @brief Stores the top-level information for the XML section of the file. struct E57_DLL E57Root { - ustring formatName; //!< Contains the string "ASTM E57 3D Image File" - ustring guid; //!< A globally unique identification string for the current version of the file - uint32_t versionMajor{ 1 }; //!< Major version number, should be 1 - uint32_t versionMinor{ 0 }; //!< Minor version number, should be 0 - ustring e57LibraryVersion; //!< The version identifier for the E57 file format library that wrote the file. - DateTime creationDateTime; //!< Date/time that the file was created - int64_t data3DSize{ 0 }; //!< Size of the Data3D vector for storing 3D imaging data - int64_t images2DSize{ 0 }; //!< Size of the A heterogeneous Vector of Images2D Structures for storing 2D images - //!< from a camera or similar device. - ustring coordinateMetadata; //!< Information describing the Coordinate Reference System to be used for the file + /// Must contain the string "ASTM E57 3D Imaging Data File" + ustring formatName; + + /// A globally unique identification string for the current version of the file + ustring guid; + + /// Major version number (should be 1) + uint32_t versionMajor = 1; + /// Minor version number (should be 0) + uint32_t versionMinor = 0; + + /// The version identifier for the E57 file format library which wrote the file. + ustring e57LibraryVersion; + + /// Date/time that the file was created + DateTime creationDateTime; + + /// Size of the Data3D vector for storing 3D imaging data + int64_t data3DSize = 0; + + /// Size of the Images2D vector for storing 2D images from a camera or similar device. + int64_t images2DSize = 0; + + /// Information describing the Coordinate Reference System to be used for the file + ustring coordinateMetadata; }; - //! @brief Stores information about a single group of points in a row or column + /// @brief Stores information about a single group of points in a row or column struct E57_DLL LineGroupRecord { - int64_t idElementValue{ - 0 - }; //!< The value of the identifying element of all members in this group. Shall be in the interval [0, 2^63). - int64_t startPointIndex{ - 0 - }; //!< The record number of the first point in the continuous interval. Shall be in the interval [0, 2^63). - int64_t pointCount{ - 0 - }; //!< The number of PointRecords in the group. Shall be in the interval [1, 2^63). May be zero. - CartesianBounds cartesianBounds; //!< The bounding box (in Cartesian coordinates) of all points in the group - //!< (in the local coordinate system of the points). - SphericalBounds sphericalBounds; //!< The bounding region (in spherical coordinates) of all the points in the - //!< group (in the local coordinate system of the points). + /// @brief The value of the identifying element of all members in this group. + /// @details Shall be in the interval [0, 2^63). + int64_t idElementValue = 0; + + /// @brief The record number of the first point in the continuous interval. + /// @details Shall be in the interval [0, 2^63). + int64_t startPointIndex = 0; + + /// @brief The number of PointRecords in the group. + /// @details Shall be in the interval [1, 2^63). May be zero. + int64_t pointCount = 0; + + /// @brief The bounding box (in Cartesian coordinates) of all points in the group. + /// @details These are in the local coordinate system of the points. + CartesianBounds cartesianBounds; + + /// @brief The bounding region (in spherical coordinates) of all the points in the group. + /// @details These are in the local coordinate system of the points. + SphericalBounds sphericalBounds; }; - //! @brief Stores a set of point groups organized by the rowIndex or columnIndex attribute of the PointRecord + /// @brief Stores a set of point groups organized by the rowIndex or columnIndex attribute of the + /// PointRecord struct E57_DLL GroupingByLine { - ustring idElementName; //!< The name of the PointRecord element that identifies which group the point is in. The - //!< value of this string must be "rowIndex" or "columnIndex" - int64_t groupsSize{ 0 }; //!< Size of the groups compressedVector of LineGroupRecord structures - int64_t pointCountSize{ 0 }; //!< This is the size value for the LineGroupRecord::pointCount. + /// @brief The name of the PointRecord element that identifies which group the point is in. + /// @details The value of this string must be "rowIndex" or "columnIndex". + ustring idElementName; + + /// @brief Size of the groups compressedVector of LineGroupRecord structures. + int64_t groupsSize = 0; + + /// @brief The size value for the LineGroupRecord::pointCount. + int64_t pointCountSize = 0; }; - //! @brief Supports the division of points within an Data3D into logical groupings + /// @brief Supports the division of points within an Data3D into logical groupings struct E57_DLL PointGroupingSchemes { - GroupingByLine groupingByLine; //!< Grouping information by row or column index + /// @brief Grouping information by row or column index + GroupingByLine groupingByLine; + }; + + /// @brief Used to set the type of node in some PointStandardizedFieldsAvailable fields. + enum class NumericalNodeType + { + Integer = 0, ///< Use IntegerNode + ScaledInteger, ///< Use ScaledIntegerNode + Float, ///< Use FloatNode with floats + Double, ///< Use FloatNode with doubles }; - //! @brief Used to interrogate if standardized fields are available + /// @brief Used to interrogate if standardized fields are available struct E57_DLL PointStandardizedFieldsAvailable { - bool cartesianXField{ false }; //!< Indicates that the PointRecord cartesianX field is active - bool cartesianYField{ false }; //!< Indicates that the PointRecord cartesianY field is active - bool cartesianZField{ false }; //!< Indicates that the PointRecord cartesianZ field is active - bool cartesianInvalidStateField{ - false - }; //!< Indicates that the PointRecord cartesianInvalidState field is active - - bool sphericalRangeField{ false }; //!< Indicates that the PointRecord sphericalRange field is active - bool sphericalAzimuthField{ false }; //!< Indicates that the PointRecord sphericalAzimuth field is active - bool sphericalElevationField{ false }; //!< Indicates that the PointRecord sphericalElevation field is active - bool sphericalInvalidStateField{ - false - }; //!< Indicates that the PointRecord sphericalInvalidState field is active - - double pointRangeMinimum{ - E57_FLOAT_MIN - }; //!< Indicates that the PointRecord cartesian and range fields should be configured with this minimum value - //!< -E57_FLOAT_MAX or -E57_DOUBLE_MAX. If using a ScaledIntegerNode then this needs to be a minimum range - //!< value. - double pointRangeMaximum{ - E57_FLOAT_MAX - }; //!< Indicates that the PointRecord cartesian and range fields should be configured with this maximum value - //!< E57_FLOAT_MAX or E57_DOUBLE_MAX. If using a ScaledIntegerNode then this needs to be a maximum range value. - double pointRangeScaledInteger{ - E57_NOT_SCALED_USE_FLOAT - }; //!< Indicates that the PointRecord cartesain and range fields should be configured as a ScaledIntegerNode with - //!< this scale setting. If 0. then use FloatNode. - - double angleMinimum{ - E57_FLOAT_MIN - }; //!< Indicates that the PointRecord angle fields should be configured with this minimum value -E57_FLOAT_MAX or - //!< -E57_DOUBLE_MAX. If using a ScaledIntegerNode then this needs to be a minimum angle value. - double angleMaximum{ - E57_FLOAT_MAX - }; //!< Indicates that the PointRecord angle fields should be configured with this maximum value E57_FLOAT_MAX or - //!< E57_DOUBLE_MAX. If using a ScaledIntegerNode then this needs to be a maximum angle value. - double angleScaledInteger{ - E57_NOT_SCALED_USE_FLOAT - }; //!< Indicates that the PointRecord angle fields should be configured as a ScaledIntegerNode with this scale - //!< setting. If 0. then use FloatNode. - - bool rowIndexField{ false }; //!< Indicates that the PointRecord rowIndex field is active - uint32_t rowIndexMaximum{ E57_UINT32_MAX }; //!< Indicates that the PointRecord index fields should be configured - //!< with this maximum value where the minimum will be set to 0. - bool columnIndexField{ false }; //!< Indicates that the PointRecord columnIndex field is active - uint32_t columnIndexMaximum{ - E57_UINT32_MAX - }; //!< Indicates that the PointRecord index fields should be configured with this maximum value where the minimum - //!< will be set to 0. - - bool returnIndexField{ false }; //!< Indicates that the PointRecord returnIndex field is active - bool returnCountField{ false }; //!< Indicates that the PointRecord returnCount field is active - uint8_t returnMaximum{ E57_UINT8_MAX }; //!< Indicates that the PointRecord return fields should be configured - //!< with this maximum value where the minimum will be set to 0. - - bool timeStampField{ false }; //!< Indicates that the PointRecord timeStamp field is active - bool isTimeStampInvalidField{ false }; //!< Indicates that the PointRecord isTimeStampInvalid field is active - double timeMaximum{ - E57_DOUBLE_MAX - }; //!< Indicates that the PointRecord timeStamp fields should be configured with this maximum value. like - //!< E57_UINT32_MAX, E57_FLOAT_MAX or E57_DOUBLE_MAX - double timeMinimum{ E57_DOUBLE_MIN }; //!< Indicates that the PointRecord timeStamp fields should be configured - //!< with this minimum value -E57_FLOAT_MAX or -E57_DOUBLE_MAX. If using a - //!< ScaledIntegerNode then this needs to be a minimum time value. - double timeScaledInteger{ - E57_NOT_SCALED_USE_FLOAT - }; //!< Indicates that the PointRecord timeStamp fields should be configured as a ScaledIntegerNode with this - //!< scale setting. If 0. then use FloatNode, if -1. use IntegerNode. - - bool intensityField{ false }; //!< Indicates that the PointRecord intensity field is active - bool isIntensityInvalidField{ false }; //!< Indicates that the PointRecord isIntensityInvalid field is active - double intensityScaledInteger{ - E57_NOT_SCALED_USE_INTEGER - }; //!< Indicates that the PointRecord intensity fields should be configured as a ScaledIntegerNode with this - //!< setting. If 0. then use FloatNode, if -1. use IntegerNode - - bool colorRedField{ false }; //!< indicates that the PointRecord colorRed field is active - bool colorGreenField{ false }; //!< indicates that the PointRecord colorGreen field is active - bool colorBlueField{ false }; //!< indicates that the PointRecord colorBlue field is active - bool isColorInvalidField{ false }; //!< Indicates that the PointRecord isColorInvalid field is active - - bool normalX{ false }; //!< Indicates that the PointRecord nor:normalX field is active - bool normalY{ false }; //!< Indicates that the PointRecord nor:normalY field is active - bool normalZ{ false }; //!< Indicates that the PointRecord nor:normalZ field is active + /// Indicates that the PointRecord cartesianX field is active + bool cartesianXField = false; + /// Indicates that the PointRecord cartesianY field is active + bool cartesianYField = false; + /// Indicates that the PointRecord cartesianZ field is active + bool cartesianZField = false; + /// Indicates that the PointRecord cartesianInvalidState field is active + bool cartesianInvalidStateField = false; + + /// Indicates that the PointRecord sphericalRange field is active + bool sphericalRangeField = false; + /// Indicates that the PointRecord sphericalAzimuth field is active + bool sphericalAzimuthField = false; + /// Indicates that the PointRecord sphericalElevation field is active + bool sphericalElevationField = false; + /// Indicates that the PointRecord sphericalInvalidState field is active + bool sphericalInvalidStateField = false; + + /// @brief Indicates that the PointRecord cartesian and range fields should be configured with + /// this minimum value e.g. E57_FLOAT_MIN or E57_DOUBLE_MIN. + /// @details If using a ScaledIntegerNode then this needs to be a minimum range value. + double pointRangeMinimum = DOUBLE_MIN; + + /// @brief Indicates that the PointRecord cartesian and range fields should be configured with + /// this maximum value e.g. E57_FLOAT_MAX or E57_DOUBLE_MAX. + /// @details If using a ScaledIntegerNode then this needs to be a maximum range value. + double pointRangeMaximum = DOUBLE_MAX; + + /// @brief Controls the type of Node used for the PointRecord cartesian and range fields + /// @details Accepts NumericalNodeType::ScaledInteger, NumericalNodeType::Float, and + /// NumericalNodeType::Double. + NumericalNodeType pointRangeNodeType = NumericalNodeType::Float; + + /// @brief Sets the scale if using scaled integers for point fields + /// @details If pointRangeNodeType == NumericalNodeType::ScaledInteger, it will use this value + /// to scale the numbers and it must be > 0.0. + double pointRangeScale = 0.0; + + /// @brief Indicates that the PointRecord angle fields should be configured with this minimum + /// value E57_FLOAT_MIN or E57_DOUBLE_MIN. + /// @details If using a ScaledIntegerNode then this needs to be a minimum angle value. + double angleMinimum = DOUBLE_MIN; + + /// @brief Indicates that the PointRecord angle fields should be configured with this maximum + /// value e.g. E57_FLOAT_MAX or E57_DOUBLE_MAX. + /// @details If using a ScaledIntegerNode then this needs to be a maximum angle value. + double angleMaximum = DOUBLE_MAX; + + /// @brief Controls the type of Node used for the PointRecord angle fields + /// @details Accepts NumericalNodeType::ScaledInteger, NumericalNodeType::Float, and + /// NumericalNodeType::Double. + NumericalNodeType angleNodeType = NumericalNodeType::Float; + + /// @brief Sets the scale if using scaled integers for angle fields + /// @details If angleNodeType == NumericalNodeType::ScaledInteger, it will use this value + /// to scale the numbers and it must be > 0.0. + double angleScale = 0.0; + + /// Indicates that the PointRecord @a rowIndex field is active + bool rowIndexField = false; + + /// Indicates that the PointRecord @a rowIndex fields should be configured with this maximum + /// value where the minimum will be set to 0. + uint32_t rowIndexMaximum = UINT32_MAX; + + /// Indicates that the PointRecord @a columnIndex field is active + bool columnIndexField = false; + + /// Indicates that the PointRecord @a columnIndex fields should be configured with this + /// maximum value where the minimum will be set to 0. + uint32_t columnIndexMaximum = UINT32_MAX; + + /// Indicates that the PointRecord @a returnIndex field is active + bool returnIndexField = false; + /// Indicates that the PointRecord @a returnCount field is active + bool returnCountField = false; + /// Indicates that the PointRecord return fields should be configured with this maximum value + /// where the minimum will be set to 0. + uint8_t returnMaximum = UINT8_MAX; + + /// Indicates that the PointRecord @a timeStamp field is active + bool timeStampField = false; + /// Indicates that the PointRecord @a isTimeStampInvalid field is active + bool isTimeStampInvalidField = false; + + /// @brief Indicates that the PointRecord @a timeStamp fields should be configured with this + /// minimum value e.g. E57_UINT32_MIN, E57_DOUBLE_MIN or E57_DOUBLE_MIN. + /// @details If using a ScaledIntegerNode then this needs to be a minimum time value. + double timeMinimum = DOUBLE_MIN; + + /// Indicates that the PointRecord @a timeStamp fields should be configured with this maximum + /// value. e.g. E57_UINT32_MAX, E57_DOUBLE_MAX or E57_DOUBLE_MAX. + double timeMaximum = DOUBLE_MAX; + + /// @brief Controls the type of Node used for the PointRecord time fields + /// @details Accepts NumericalNodeType::Integer, NumericalNodeType::ScaledInteger, + /// NumericalNodeType::Float, and NumericalNodeType::Double. + NumericalNodeType timeNodeType = NumericalNodeType::Float; + + /// @brief Sets the scale if using scaled integers for time fields + /// @details If timeNodeType == NumericalNodeType::ScaledInteger, it will use this value + /// to scale the numbers and it must be > 0.0. + double timeScale = 0.0; + + /// Indicates that the PointRecord @a intensity field is active + bool intensityField = false; + /// Indicates that the PointRecord @a isIntensityInvalid field is active + bool isIntensityInvalidField = false; + + /// @brief Controls the type of Node used for the PointRecord intensity fields + /// @details Accepts NumericalNodeType::Integer, NumericalNodeType::ScaledInteger, + /// NumericalNodeType::Float, and NumericalNodeType::Double. + NumericalNodeType intensityNodeType = NumericalNodeType::Float; + + /// @brief Sets the scale if using scaled integers for intensity fields + /// @details If intensityNodeType == NumericalNodeType::ScaledInteger, it will use this value + /// to scale the numbers and it must be > 0.0. + double intensityScale = 0.0; + + /// Indicates that the PointRecord @a colorRed field is active + bool colorRedField = false; + /// Indicates that the PointRecord @a colorGreen field is active + bool colorGreenField = false; + /// Indicates that the PointRecord @a colorBlue field is active + bool colorBlueField = false; + /// Indicates that the PointRecord @a isColorInvalid field is active + bool isColorInvalidField = false; + + /// Indicates that the PointRecord @a nor:normalX field is active + bool normalXField = false; + /// Indicates that the PointRecord @a nor:normalY field is active + bool normalYField = false; + /// Indicates that the PointRecord @a nor:normalZ field is active + bool normalZField = false; }; - //! @brief Stores the top-level information for a single lidar scan + /// @brief Stores the top-level information for a single lidar scan struct E57_DLL Data3D { - ustring name; //!< A user-defined name for the Data3D. - ustring guid; //!< A globally unique identification string for the current version of the Data3D object - std::vector originalGuids; //!< A vector of globally unique identification Strings from which the points - //!< in this Data3D originated. - ustring description; //!< A user-defined description of the Image - - ustring sensorVendor; //!< The name of the manufacturer for the sensor used to collect the points in this Data3D. - ustring sensorModel; //!< The model name or number for the sensor. - ustring sensorSerialNumber; //!< The serial number for the sensor. - ustring sensorHardwareVersion; //!< The version number for the sensor hardware at the time of data collection. - ustring sensorSoftwareVersion; //!< The version number for the software used for the data collection. - ustring sensorFirmwareVersion; //!< The version number for the firmware installed in the sensor at the time of - //!< data collection. - - float temperature{ E57_FLOAT_MAX }; //!< The ambient temperature, measured at the sensor, at the time of data - //!< collection (in degrees Celsius). - float relativeHumidity{ E57_FLOAT_MAX }; //!< The percentage relative humidity, measured at the sensor, at the - //!< time of data collection. Shall be in the interval [0, 100]. - float atmosphericPressure{ E57_FLOAT_MAX }; //!< The atmospheric pressure, measured at the sensor, at the time of - //!< data collection (in Pascals). Shall be positive. - - DateTime acquisitionStart; //!< The start date and time that the data was acquired. - DateTime acquisitionEnd; //!< The end date and time that the data was acquired. - - RigidBodyTransform pose; //!< A rigid body transform that describes the coordinate frame of the 3D imaging - //!< system origin in the file-level coordinate system. - IndexBounds indexBounds; //!< The bounds of the row, column, and return number of all the points in this Data3D. - CartesianBounds cartesianBounds; //!< The bounding region (in cartesian coordinates) of all the points in - //!< this Data3D (in the local coordinate system of the points). - SphericalBounds sphericalBounds; //!< The bounding region (in spherical coordinates) of all the points in - //!< this Data3D (in the local coordinate system of the points). - IntensityLimits - intensityLimits; //!< The limits for the value of signal intensity that the sensor is capable of producing. - ColorLimits colorLimits; //!< The limits for the value of red, green, and blue color that the sensor is - //!< capable of producing. - - PointGroupingSchemes pointGroupingSchemes; //!< The defined schemes that group points in different ways - PointStandardizedFieldsAvailable - pointFields; //!< This defines the active fields used in the WritePoints function. - - int64_t pointsSize{ 0 }; //!< Total size of the compressed vector of PointRecord structures referring to the - //!< binary data that actually stores the point data + /// A user-defined name for the Data3D. + ustring name; + + /// A globally unique identification string for the current version of the Data3D object + ustring guid; + + /// @brief A vector of globally unique identification Strings from which the points in this + /// Data3D originated. + std::vector originalGuids; + + /// A user-defined description of the Image + ustring description; + + /// The name of the manufacturer for the sensor used to collect the points in this Data3D. + ustring sensorVendor; + /// The model name or number for the sensor. + ustring sensorModel; + /// The serial number for the sensor. + ustring sensorSerialNumber; + /// The version number for the sensor hardware at the time of data collection. + ustring sensorHardwareVersion; + /// The version number for the software used for the data collection. + ustring sensorSoftwareVersion; + /// @brief The version number for the firmware installed in the sensor at the time of data + /// collection. + ustring sensorFirmwareVersion; + + /// @brief The ambient temperature, measured at the sensor, at the time of data collection. + /// @details This units are degrees Celsius. + float temperature = FLOAT_MAX; + + /// @brief The percentage relative humidity, measured at the sensor, at the time of data + /// collection. + /// @details Shall be in the interval [0, 100]. + float relativeHumidity = FLOAT_MAX; + + /// @brief The atmospheric pressure, measured at the sensor, at the time of data collection + /// @details The units are Pascals. Shall be positive. + float atmosphericPressure = FLOAT_MAX; + + /// The start date and time that the data was acquired. + DateTime acquisitionStart; + /// The end date and time that the data was acquired. + DateTime acquisitionEnd; + + /// @brief A rigid body transform that describes the coordinate frame of the 3D imaging system + /// origin. + /// @details These are in the file-level coordinate system. + RigidBodyTransform pose; + + /// The bounds of the row, column, and return number of all the points in this Data3D. + IndexBounds indexBounds; + + /// @brief The bounding region (in cartesian coordinates) of all the points in this Data3D. + /// @details These are in the local coordinate system of the points. + CartesianBounds cartesianBounds; + + /// @brief The bounding region (in spherical coordinates) of all the points in this Data3D. + /// @details These are in the local coordinate system of the points. + SphericalBounds sphericalBounds; + + /// The limits for the value of signal intensity that the sensor is capable of producing. + IntensityLimits intensityLimits; + + /// @brief The limits for the value of red, green, and blue color that the sensor is capable + /// of producing. + ColorLimits colorLimits; + + /// The defined schemes that group points in different ways + PointGroupingSchemes pointGroupingSchemes; + /// The active fields used in the WritePoints function. + PointStandardizedFieldsAvailable pointFields; + + /// The number of points in the Data3D. + /// On 32-bit systems size_t will allow for 4,294,967,295 points per scan which seems + /// reasonable... + size_t pointCount = 0; }; - //! @brief Stores pointers to user-provided buffers - template struct Data3DPointsData_t + /// @brief Stores pointers to user-provided buffers + template struct Data3DPointsData_t { - COORDTYPE *cartesianX{ - nullptr - }; //!< pointer to a buffer with the X coordinate (in meters) of the point in Cartesian coordinates - COORDTYPE *cartesianY{ - nullptr - }; //!< pointer to a buffer with the Y coordinate (in meters) of the point in Cartesian coordinates - COORDTYPE *cartesianZ{ - nullptr - }; //!< pointer to a buffer with the Z coordinate (in meters) of the point in Cartesian coordinates - int8_t *cartesianInvalidState{ nullptr }; //!< Value = 0 if the point is considered valid, 1 otherwise - - float *intensity{ nullptr }; //!< pointer to a buffer with the Point response intensity. Unit is unspecified - int8_t *isIntensityInvalid{ nullptr }; //!< Value = 0 if the intensity is considered valid, 1 otherwise - - uint8_t *colorRed{ nullptr }; //!< pointer to a buffer with the Red color coefficient. Unit is unspecified - uint8_t *colorGreen{ nullptr }; //!< pointer to a buffer with the Green color coefficient. Unit is unspecified - uint8_t *colorBlue{ nullptr }; //!< pointer to a buffer with the Blue color coefficient. Unit is unspecified - int8_t *isColorInvalid{ nullptr }; //!< Value = 0 if the color is considered valid, 1 otherwise - - COORDTYPE *sphericalRange{ - nullptr - }; //!< pointer to a buffer with the range (in meters) of points in spherical coordinates. Shall be non-negative - COORDTYPE *sphericalAzimuth{ - nullptr - }; //!< pointer to a buffer with the Azimuth angle (in radians) of point in spherical coordinates - COORDTYPE *sphericalElevation{ - nullptr - }; //!< pointer to a buffer with the Elevation angle (in radians) of point in spherical coordinates - int8_t *sphericalInvalidState{ nullptr }; //!< Value = 0 if the range is considered valid, 1 otherwise - - int32_t *rowIndex{ nullptr }; //!< pointer to a buffer with the row number of point (zero based). This is useful - //!< for data that is stored in a regular grid. Shall be in the interval (0, 2^31). - int32_t *columnIndex{ - nullptr - }; //!< pointer to a buffer with the column number of point (zero based). This is useful for data that is stored - //!< in a regular grid. Shall be in the interval (0, 2^31). - int8_t *returnIndex{ - nullptr - }; //!< pointer to a buffer with the number of this return (zero based). That is, 0 is the first return, 1 is the - //!< second, and so on. Shall be in the interval (0, returnCount). Only for multi-return sensors. - int8_t *returnCount{ - nullptr - }; //!< pointer to a buffer with the total number of returns for the pulse that this corresponds to. Shall be in - //!< the interval (0, 2^7). Only for multi-return sensors. - - double *timeStamp{ - nullptr - }; //!< pointer to a buffer with the time (in seconds) since the start time for the data, which is given by - //!< acquisitionStart in the parent Data3D Structure. Shall be non-negative - int8_t *isTimeStampInvalid{ nullptr }; //!< Value = 0 if the timeStamp is considered valid, 1 otherwise - - // E57_EXT_surface_normals - float *normalX{ nullptr }; //!< The X component of a surface normal vector (E57_EXT_surface_normals). - float *normalY{ nullptr }; //!< The Y component of a surface normal vector (E57_EXT_surface_normals). - float *normalZ{ nullptr }; //!< The Z component of a surface normal vector (E57_EXT_surface_normals). + static_assert( std::is_floating_point::value, "Floating point type required." ); + + /// @brief Default constructor does not manage any memory, adjust min/max for floats, or + /// validate data. + Data3DPointsData_t() = default; + + /*! + @brief Constructor which allocates buffers for all valid fields in the given Data3D header. + + @details + This constructor will also adjust the min/max fields in the data3D pointFields if + we are using floats, and run some validation on the Data3D. + + @param [in] data3D Completed header which indicates the fields we are using + + @throw ::ErrorValueOutOfBounds + @throw ::ErrorInvalidNodeType + */ + explicit Data3DPointsData_t( e57::Data3D &data3D ); + + /// @brief Destructor will delete any memory allocated using the Data3DPointsData_t( const + /// e57::Data3D & ) constructor + ~Data3DPointsData_t(); + + /// @brief Pointer to a buffer with the X coordinate (in meters) of the point in Cartesian + /// coordinates + COORDTYPE *cartesianX = nullptr; + + /// @brief Pointer to a buffer with the Y coordinate (in meters) of the point in Cartesian + /// coordinates + COORDTYPE *cartesianY = nullptr; + + /// @brief Pointer to a buffer with the Z coordinate (in meters) of the point in Cartesian + /// coordinates + COORDTYPE *cartesianZ = nullptr; + + /// @brief Value = 0 if the point is considered valid, 1 otherwise + int8_t *cartesianInvalidState = nullptr; + + /// @brief Pointer to a buffer with the Point response intensity. Unit is unspecified. + double *intensity = nullptr; + + /// @brief Value = 0 if the intensity is considered valid, 1 otherwise + int8_t *isIntensityInvalid = nullptr; + + /// @brief Pointer to a buffer with the Red color coefficient. Unit is unspecified + uint16_t *colorRed = nullptr; + /// @brief Pointer to a buffer with the Green color coefficient. Unit is unspecified + uint16_t *colorGreen = nullptr; + /// @brief Pointer to a buffer with the Blue color coefficient. Unit is unspecified + uint16_t *colorBlue = nullptr; + /// @brief Value = 0 if the color is considered valid, 1 otherwise + int8_t *isColorInvalid = nullptr; + + /// @brief Pointer to a buffer with the range (in meters) of points in spherical coordinates. + COORDTYPE *sphericalRange = nullptr; + + /// @brief Pointer to a buffer with the Azimuth angle (in radians) of point in spherical + /// coordinates + COORDTYPE *sphericalAzimuth = nullptr; + + /// @brief Pointer to a buffer with the Elevation angle (in radians) of point in spherical + /// coordinates + COORDTYPE *sphericalElevation = nullptr; + + /// @brief Value = 0 if the range is considered valid, 1 otherwise + int8_t *sphericalInvalidState = nullptr; + + /// @brief Pointer to a buffer with the row number of point (zero based). + /// @details This is useful for data that is stored in a regular grid. Shall be in the + /// interval (0, 2^31). + int32_t *rowIndex = nullptr; + + /// @brief Pointer to a buffer with the column number of point (zero based). + /// @details This is useful for data that is stored in a regular grid. Shall be in the + /// interval (0, 2^31). + int32_t *columnIndex = nullptr; + + /// @brief Pointer to a buffer with the number of this return (zero based). + /// @details That is, 0 is the first return, 1 is the second, and so on. Shall be in the + /// interval (0, returnCount). Only for multi-return sensors. + int8_t *returnIndex = nullptr; + + /// @brief Pointer to a buffer with the total number of returns for the pulse that this + /// corresponds to. + /// @details Shall be in the interval (0, 2^7). Only for multi-return sensors. + int8_t *returnCount = nullptr; + + /// @brief Pointer to a buffer with the time (in seconds) since the start time for the data. + /// @details This is given by acquisitionStart in the parent Data3D Structure. + double *timeStamp = nullptr; + + /// @brief Value = 0 if the timeStamp is considered valid, 1 otherwise + int8_t *isTimeStampInvalid = nullptr; + + /// @name Extension: E57_EXT_surface_normals + /// The following fields are part of the + /// [E57_EXT_surface_normals](http://www.libe57.org/E57_EXT_surface_normals.txt) extension. + ///@{ + + /// @brief The X component of a surface normal vector. + float *normalX = nullptr; + /// @brief The Y component of a surface normal vector. + float *normalY = nullptr; + /// @brief The Z component of a surface normal vector. + float *normalZ = nullptr; + + ///@} + + private: + /// @brief Keeps track of whether we used the Data3D constructor or not so we can free our + /// memory. + bool _selfAllocated = false; }; - typedef Data3DPointsData_t Data3DPointsData; - typedef Data3DPointsData_t Data3DPointsData_d; + using Data3DPointsFloat = Data3DPointsData_t; + using Data3DPointsDouble = Data3DPointsData_t; + + /// @deprecated Will be removed in 4.0. Use e57::Data3DPointsFloat. + using Data3DPointsData [[deprecated( "Will be removed in 4.0. Use Data3DPointsFloat." )]] = + Data3DPointsData_t; + /// @deprecated Will be removed in 4.0. Use e57::Data3DPointsDouble. + using Data3DPointsData_d [[deprecated( "Will be removed in 4.0. Use Data3DPointsDouble." )]] = + Data3DPointsData_t; + + extern template struct Data3DPointsData_t; + extern template struct Data3DPointsData_t; - //! @brief Stores an image that is to be used only as a visual reference. + /// @brief Stores an image that is to be used only as a visual reference. struct E57_DLL VisualReferenceRepresentation { - int64_t jpegImageSize{ 0 }; //!< Size of JPEG format image data in BlobNode. - int64_t pngImageSize{ 0 }; //!< Size of PNG format image data in BlobNode. - int64_t imageMaskSize{ 0 }; //!< Size of PNG format image mask in BlobNode. - int32_t imageWidth{ 0 }; //!< The image width (in pixels). Shall be positive - int32_t imageHeight{ 0 }; //!< The image height (in pixels). Shall be positive + /// Size of JPEG format image data in BlobNode. + int64_t jpegImageSize = 0; + + /// Size of PNG format image data in BlobNode. + int64_t pngImageSize = 0; + + /// Size of PNG format image mask in BlobNode. + int64_t imageMaskSize = 0; + + /// The image width (in pixels). Shall be positive. + int32_t imageWidth = 0; + + /// The image height (in pixels). Shall be positive. + int32_t imageHeight = 0; bool operator==( const VisualReferenceRepresentation &rhs ) const { @@ -512,28 +771,44 @@ namespace e57 ( imageMaskSize == rhs.imageMaskSize ) && ( imageWidth == rhs.imageWidth ) && ( imageHeight == rhs.imageHeight ); } + bool operator!=( const VisualReferenceRepresentation &rhs ) const { return !operator==( rhs ); } }; - //! @brief Stores an image that is mapped from 3D using the pinhole camera projection model. + /// @brief Stores an image that is mapped from 3D using the pinhole camera projection model. struct E57_DLL PinholeRepresentation { - int64_t jpegImageSize{ 0 }; //!< Size of JPEG format image data in BlobNode. - int64_t pngImageSize{ 0 }; //!< Size of PNG format image data in BlobNode. - int64_t imageMaskSize{ 0 }; //!< Size of PNG format image mask in BlobNode. - int32_t imageWidth{ 0 }; //!< The image width (in pixels). Shall be positive - int32_t imageHeight{ 0 }; //!< The image height (in pixels). Shall be positive - double focalLength{ 0. }; //!< The camera's focal length (in meters). Shall be positive - double pixelWidth{ 0. }; //!< The width of the pixels in the camera (in meters). Shall be positive - double pixelHeight{ 0. }; //!< The height of the pixels in the camera (in meters). Shall be positive - double principalPointX{ - 0. - }; //!< The X coordinate in the image of the principal point, (in pixels). The principal point is the intersection - //!< of the z axis of the camera coordinate frame with the image plane. - double principalPointY{ 0. }; //!< The Y coordinate in the image of the principal point (in pixels). + /// Size of JPEG format image data in BlobNode. + int64_t jpegImageSize = 0; + + /// Size of PNG format image data in BlobNode. + int64_t pngImageSize = 0; + + /// Size of PNG format image mask in BlobNode. + int64_t imageMaskSize = 0; + + /// The image width (in pixels). Shall be positive. + int32_t imageWidth = 0; + /// The image height (in pixels). Shall be positive. + int32_t imageHeight = 0; + + /// The camera's focal length (in meters). Shall be positive. + double focalLength = 0.0; + + /// The width of the pixels in the camera (in meters). Shall be positive. + double pixelWidth = 0.0; + /// The height of the pixels in the camera (in meters). Shall be positive. + double pixelHeight = 0.0; + + /// @brief The X coordinate in the image of the principal point, (in pixels). + /// @details The principal point is the intersection of the z axis of the camera coordinate + /// frame with the image plane. + double principalPointX = 0.0; + /// The Y coordinate in the image of the principal point (in pixels). + double principalPointY = 0.0; bool operator==( const PinholeRepresentation &rhs ) const { @@ -541,24 +816,37 @@ namespace e57 ( imageMaskSize == rhs.imageMaskSize ) && ( imageWidth == rhs.imageWidth ) && ( imageHeight == rhs.imageHeight ) && ( focalLength == rhs.focalLength ) && ( pixelWidth == rhs.pixelWidth ) && ( pixelHeight == rhs.pixelHeight ) && - ( principalPointX == rhs.principalPointX ) && ( principalPointY == rhs.principalPointY ); + ( principalPointX == rhs.principalPointX ) && + ( principalPointY == rhs.principalPointY ); } + bool operator!=( const PinholeRepresentation &rhs ) const { return !operator==( rhs ); } }; - //! @brief Stores an image that is mapped from 3D using a spherical projection model + /// @brief Stores an image that is mapped from 3D using a spherical projection model struct E57_DLL SphericalRepresentation { - int64_t jpegImageSize{ 0 }; //!< Size of JPEG format image data in BlobNode. - int64_t pngImageSize{ 0 }; //!< Size of PNG format image data in BlobNode. - int64_t imageMaskSize{ 0 }; //!< Size of PNG format image mask in BlobNode. - int32_t imageWidth{ 0 }; //!< The image width (in pixels). Shall be positive - int32_t imageHeight{ 0 }; //!< The image height (in pixels). Shall be positive - double pixelWidth{ 0. }; //!< The width of a pixel in the image (in radians). Shall be positive - double pixelHeight{ 0. }; //!< The height of a pixel in the image (in radians). Shall be positive. + /// Size of JPEG format image data in BlobNode. + int64_t jpegImageSize = 0; + + /// Size of PNG format image data in BlobNode. + int64_t pngImageSize = 0; + + /// Size of PNG format image mask in BlobNode. + int64_t imageMaskSize = 0; + + /// The image width (in pixels). Shall be positive + int32_t imageWidth = 0; + /// The image height (in pixels). Shall be positive + int32_t imageHeight = 0; + + /// The width of a pixel in the image (in radians). Shall be positive + double pixelWidth = 0.0; + /// The height of a pixel in the image (in radians). Shall be positive. + double pixelHeight = 0.0; bool operator==( const SphericalRepresentation &rhs ) const { @@ -567,26 +855,43 @@ namespace e57 ( imageHeight == rhs.imageHeight ) && ( pixelWidth == rhs.pixelWidth ) && ( pixelHeight == rhs.pixelHeight ); } + bool operator!=( const SphericalRepresentation &rhs ) const { return !operator==( rhs ); } }; - //! @brief Stores an image that is mapped from 3D using a cylindrical projection model. + /// @brief Stores an image that is mapped from 3D using a cylindrical projection model. struct E57_DLL CylindricalRepresentation { - int64_t jpegImageSize{ 0 }; //!< Size of JPEG format image data in Blob. - int64_t pngImageSize{ 0 }; //!< Size of PNG format image data in Blob. - int64_t imageMaskSize{ 0 }; //!< Size of PNG format image mask in Blob. - int32_t imageWidth{ 0 }; //!< The image width (in pixels). Shall be positive - int32_t imageHeight{ 0 }; //!< The image height (in pixels). Shall be positive - double pixelWidth{ 0. }; //!< The width of a pixel in the image (in radians). Shall be positive - double pixelHeight{ 0. }; //!< The height of a pixel in the image (in meters). Shall be positive - double radius{ 0. }; //!< The closest distance from the cylindrical image surface to the center of projection - //!< (that is, the radius of the cylinder) (in meters). Shall be non-negative - double principalPointY{ 0. }; //!< The Y coordinate in the image of the principal point (in pixels). This is the - //!< intersection of the z = 0 plane with the image + /// Size of JPEG format image data in Blob. + int64_t jpegImageSize = 0; + + /// Size of PNG format image data in Blob. + int64_t pngImageSize = 0; + + /// Size of PNG format image mask in Blob. + int64_t imageMaskSize = 0; + + /// The image width (in pixels). Shall be positive + int32_t imageWidth = 0; + /// The image height (in pixels). Shall be positive + int32_t imageHeight = 0; + + /// The width of a pixel in the image (in radians). Shall be positive. + double pixelWidth = 0.0; + /// The height of a pixel in the image (in meters). Shall be positive. + double pixelHeight = 0.0; + + /// @brief The closest distance from the cylindrical image surface to the center of projection + /// (that is, the radius of the cylinder) (in meters). + /// @details Shall be non-negative. + double radius = 0.0; + + /// @brief The Y coordinate in the image of the principal point (in pixels). + /// @details This is the intersection of the z = 0 plane with the image. + double principalPointY = 0.0; bool operator==( const CylindricalRepresentation &rhs ) const { @@ -596,58 +901,99 @@ namespace e57 ( pixelHeight == rhs.pixelHeight ) && ( radius == rhs.radius ) && ( principalPointY == rhs.principalPointY ); } + bool operator!=( const CylindricalRepresentation &rhs ) const { return !operator==( rhs ); } }; - //! @brief Stores an image from a camera + /// @brief Stores an image from a camera struct E57_DLL Image2D { - ustring name; //!< A user-defined name for the Image2D. - ustring guid; //!< A globally unique identification string for the current version of the Image2D object - ustring description; //!< A user-defined description of the Image2D - DateTime acquisitionDateTime; //!< The date and time that the image was taken - - ustring associatedData3DGuid; //!< The globally unique identification string (guid element) for the Data3D that - //!< was being acquired when the picture was taken - - ustring sensorVendor; //!< The name of the manufacturer for the sensor used to collect the points in this Data3D. - ustring sensorModel; //!< The model name or number for the sensor. - ustring sensorSerialNumber; //!< The serial number for the sensor. - - RigidBodyTransform pose; //!< A rigid body transform that describes the coordinate frame of the camera in the - //!< file-level coordinate system - - VisualReferenceRepresentation - visualReferenceRepresentation; //!< Representation for an image that does not define any camera projection - //!< model. The image is to be used for visual reference only - PinholeRepresentation - pinholeRepresentation; //!< Representation for an image using the pinhole camera projection model - SphericalRepresentation - sphericalRepresentation; //!< Representation for an image using the spherical camera projection model. - CylindricalRepresentation - cylindricalRepresentation; //!< Representation for an image using the cylindrical camera projection model + /// A user-defined name for the Image2D. + ustring name; + + /// A globally unique identification string for the current version of the Image2D object + ustring guid; + + /// A user-defined description of the Image2D + ustring description; + + /// The date and time that the image was taken + DateTime acquisitionDateTime; + + /// The globally unique identification string (guid element) for the Data3D that was being + /// acquired when the picture was taken + ustring associatedData3DGuid; + + /// The name of the manufacturer for the sensor used to collect the points in this Data3D. + ustring sensorVendor; + /// The model name or number for the sensor. + ustring sensorModel; + /// The serial number for the sensor. + ustring sensorSerialNumber; + + /// A rigid body transform that describes the coordinate frame of the camera in the file-level + /// coordinate system + RigidBodyTransform pose; + + /// Representation for an image that does not define any camera projection model. + /// The image is to be used for visual reference only + VisualReferenceRepresentation visualReferenceRepresentation; + + /// Representation for an image using the pinhole camera projection model. + PinholeRepresentation pinholeRepresentation; + + /// Representation for an image using the spherical camera projection model. + SphericalRepresentation sphericalRepresentation; + + /// Representation for an image using the cylindrical camera projection model. + CylindricalRepresentation cylindricalRepresentation; }; - //! @brief Identifies the format representation for the image data + /// @brief Identifies the format representation for the image data enum Image2DType { - E57_NO_IMAGE = 0, //!< No image data - E57_JPEG_IMAGE = 1, //!< JPEG format image data. - E57_PNG_IMAGE = 2, //!< PNG format image data. - E57_PNG_IMAGE_MASK = 3 //!< PNG format image mask. + ImageNone = 0, ///< No image data + ImageJPEG = 1, ///< JPEG format image data. + ImagePNG = 2, ///< PNG format image data. + ImageMaskPNG = 3, ///< PNG format image mask. + + /// @deprecated Will be removed in 4.0. Use e57::ImageNone. + E57_NO_IMAGE DEPRECATED_ENUM( "Will be removed in 4.0. Use ImageNone." ) = ImageNone, + /// @deprecated Will be removed in 4.0. Use e57::ImageJPEG. + E57_JPEG_IMAGE DEPRECATED_ENUM( "Will be removed in 4.0. Use ImageJPEG." ) = ImageJPEG, + /// @deprecated Will be removed in 4.0. Use e57::ImagePNG. + E57_PNG_IMAGE DEPRECATED_ENUM( "Will be removed in 4.0. Use ImagePNG." ) = ImagePNG, + /// @deprecated Will be removed in 4.0. Use e57::ImageMaskPNG. + E57_PNG_IMAGE_MASK DEPRECATED_ENUM( "Will be removed in 4.0. Use ImageMaskPNG." ) = + ImageMaskPNG, }; - //! @brief Identifies the representation for the image data + /// @brief Identifies the representation for the image data enum Image2DProjection { - E57_NO_PROJECTION = 0, //!< No representation for the image data is present - E57_VISUAL = 1, //!< VisualReferenceRepresentation for the image data - E57_PINHOLE = 2, //!< PinholeRepresentation for the image data - E57_SPHERICAL = 3, //!< SphericalRepresentation for the image data - E57_CYLINDRICAL = 4 //!< CylindricalRepresentation for the image data + ProjectionNone = 0, ///< No representation for the image data is present + ProjectionVisual = 1, ///< VisualReferenceRepresentation for the image data + ProjectionPinhole = 2, ///< PinholeRepresentation for the image data + ProjectionSpherical = 3, ///< SphericalRepresentation for the image data + ProjectionCylindrical = 4, ///< CylindricalRepresentation for the image data + + /// @deprecated Will be removed in 4.0. Use e57::ProjectionNone. + E57_NO_PROJECTION DEPRECATED_ENUM( "Will be removed in 4.0. Use ProjectionNone." ) = + ProjectionNone, + /// @deprecated Will be removed in 4.0. Use e57::ProjectionVisual. + E57_VISUAL DEPRECATED_ENUM( "Will be removed in 4.0. Use ProjectionVisual." ) = + ProjectionVisual, + /// @deprecated Will be removed in 4.0. Use e57::ProjectionPinhole. + E57_PINHOLE DEPRECATED_ENUM( "Will be removed in 4.0. Use ProjectionPinhole." ) = + ProjectionPinhole, + /// @deprecated Will be removed in 4.0. Use e57::ProjectionSpherical. + E57_SPHERICAL DEPRECATED_ENUM( "Will be removed in 4.0. Use ProjectionSpherical." ) = + ProjectionSpherical, + /// @deprecated Will be removed in 4.0. Use e57::ProjectionCylindrical. + E57_CYLINDRICAL DEPRECATED_ENUM( "Will be removed in 4.0. Use ProjectionCylindrical." ) = + ProjectionCylindrical, }; - } // end namespace e57 diff --git a/src/3rdParty/libE57Format/include/E57SimpleReader.h b/src/3rdParty/libE57Format/include/E57SimpleReader.h index a79afb9a39488..76db74693b366 100644 --- a/src/3rdParty/libE57Format/include/E57SimpleReader.h +++ b/src/3rdParty/libE57Format/include/E57SimpleReader.h @@ -3,6 +3,7 @@ * * Copyright (c) 2010 Stan Coleby (scoleby@intelisum.com) * Copyright (c) 2020 PTC Inc. + * Copyright (c) 2022 Andy Maloney * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by @@ -29,158 +30,185 @@ #pragma once -//! @file E57SimpleReader.h E57 Simple API for reading E57 +/// @file +/// @brief E57 Simple API for reading E57. +/// @details This includes support for the +/// [E57_EXT_surface_normals](http://www.libe57.org/E57_EXT_surface_normals.txt) extension. #include "E57SimpleData.h" namespace e57 { - - //! @brief Used for reading of the E57 file with E57 Simple API + /// Options to the Reader constructor + struct E57_DLL ReaderOptions + { + /// Set how frequently to verify the checksums (see ReadChecksumPolicy). + ReadChecksumPolicy checksumPolicy = ChecksumAll; + }; + + /// @brief Used for reading an E57 file using E57 Simple API. + /// + /// The Reader includes support for the + /// [E57_EXT_surface_normals](http://www.libe57.org/E57_EXT_surface_normals.txt) extension. class E57_DLL Reader { public: - //! @brief This function is the constructor for the reader class - //! @param [in] filePath file path to E57 file - Reader( const ustring &filePath ); - //! @brief This function returns true if the file is open + /// @brief Reader constructor + /// @param [in] filePath Path to E57 file + /// @param [in] options Options to be used for the file + Reader( const ustring &filePath, const ReaderOptions &options ); + + /// @brief Reader constructor (deprecated) + /// @param [in] filePath Path to E57 file + /// @deprecated Will be removed in 4.0. Use Reader( const ustring &, const ReaderOptions & ) + /// instead. + [[deprecated( "Will be removed in 4.0. Use Reader( const ustring, const ReaderOptions & " + ")." )]] // TODO Remove in 4.0 + explicit Reader( const ustring &filePath ); + + /// @brief Returns true if the file is open bool IsOpen() const; - //! @brief This function closes the file + /// @brief Closes the file bool Close(); - //! @name File information - //!@{ + /// @name File information + ///@{ - //! @brief This function returns the file header information - //! @param [out] fileHeader is the main header information - //! @return Returns true if successful + /// @brief Returns the file header information + /// @param [out] fileHeader is the main header information + /// @return Returns true if successful bool GetE57Root( E57Root &fileHeader ) const; - //!@} + ///@} - //! @name Image2D - //!@{ + /// @name Image2D + ///@{ - //! @brief This function returns the total number of Picture Blocks - //! @return Returns the number of Image2D blocks + /// @brief Returns the total number of Picture Blocks + /// @return Returns the number of Image2D blocks int64_t GetImage2DCount() const; - //! @brief This function returns the image2D header and positions the cursor - //! @param [in] imageIndex This in the index into the image2D vector - //! @param [out] image2DHeader pointer to the Image2D structure to receive the picture information - //! @return Returns true if successful + /// @brief Returns the image2D header and positions the cursor + /// @param [in] imageIndex This in the index into the image2D vector + /// @param [out] image2DHeader pointer to the Image2D structure to receive the picture + /// information + /// @return Returns true if successful bool ReadImage2D( int64_t imageIndex, Image2D &image2DHeader ) const; - //! @brief This function returns the size of the image data - //! @param [in] imageIndex This in the index into the image2D vector - //! @param [out] imageProjection identifies the projection in the image2D. - //! @param [out] imageType identifies the image format of the projection. - //! @param [out] imageWidth The image width (in pixels). - //! @param [out] imageHeight The image height (in pixels). - //! @param [out] imageSize This is the total number of bytes for the image blob. - //! @param [out] imageMaskType This is E57_PNG_IMAGE_MASK if "imageMask" is defined in the projection - //! @param [out] imageVisualType This is image type of the VisualReferenceRepresentation if given. - //! @return Returns true if successful - bool GetImage2DSizes( int64_t imageIndex, Image2DProjection &imageProjection, Image2DType &imageType, - int64_t &imageWidth, int64_t &imageHeight, int64_t &imageSize, Image2DType &imageMaskType, + /// @brief Returns the size of the image data + /// @param [in] imageIndex This in the index into the image2D vector + /// @param [out] imageProjection identifies the projection in the image2D. + /// @param [out] imageType identifies the image format of the projection. + /// @param [out] imageWidth The image width (in pixels). + /// @param [out] imageHeight The image height (in pixels). + /// @param [out] imageSize This is the total number of bytes for the image blob. + /// @param [out] imageMaskType This is E57_PNG_IMAGE_MASK if "imageMask" is defined in the + /// projection + /// @param [out] imageVisualType This is image type of the VisualReferenceRepresentation if + /// given. + /// @return Returns true if successful + bool GetImage2DSizes( int64_t imageIndex, Image2DProjection &imageProjection, + Image2DType &imageType, int64_t &imageWidth, int64_t &imageHeight, + int64_t &imageSize, Image2DType &imageMaskType, Image2DType &imageVisualType ) const; - //! @brief This function reads an image - //! @param [in] imageIndex index of the image. Must be less than GetImage2DCount() - //! @param [in] imageProjection identifies the projection desired. - //! @param [in] imageType identifies the image format desired. - //! @param [out] buffer pointer the raw image buffer - //! @param [in] start position in the block to start reading - //! @param [in] count size of desired chuck or buffer size - //! @return Returns the number of bytes transferred. - int64_t ReadImage2DData( int64_t imageIndex, Image2DProjection imageProjection, Image2DType imageType, - void *buffer, int64_t start, int64_t count ) const; - - //!@} - - //! @name Data3D - //!@{ - - //! @brief This function returns the total number of Data3D Blocks - //! @return Returns number of Data3D blocks. + /// @brief Reads an image + /// @param [in] imageIndex index of the image. Must be less than GetImage2DCount() + /// @param [in] imageProjection identifies the projection desired. + /// @param [in] imageType identifies the image format desired. + /// @param [out] buffer pointer the raw image buffer + /// @param [in] start position in the block to start reading + /// @param [in] count size of desired chuck or buffer size + /// @return Returns the number of bytes transferred. + int64_t ReadImage2DData( int64_t imageIndex, Image2DProjection imageProjection, + Image2DType imageType, void *buffer, int64_t start, + int64_t count ) const; + + ///@} + + /// @name Data3D + ///@{ + + /// @brief Returns the total number of Data3D Blocks + /// @return Returns number of Data3D blocks. int64_t GetData3DCount() const; - //! @brief This function returns the Data3D header - //! @param [in] dataIndex This in the index into the images3D vector. Must be less than GetData3DCount(). - //! @param [out] data3DHeader Data3D header - //! @return Returns true if successful + /// @brief Returns the Data3D header + /// @param [in] dataIndex This in the index into the images3D vector. Must be less than + /// GetData3DCount(). + /// @param [out] data3DHeader Data3D header + /// @return Returns true if successful bool ReadData3D( int64_t dataIndex, Data3D &data3DHeader ) const; - //! @brief This function returns the size of the point data - //! @param [in] dataIndex This in the index into the images3D vector. Must be less than GetData3DCount(). - //! @param [out] rowMax This is the maximum row size - //! @param [out] columnMax This is the maximum column size - //! @param [out] pointsSize This is the total number of point records - //! @param [out] groupsSize This is the total number of group reocrds - //! @param [out] countSize This is the maximum point count per group - //! @param [out] columnIndex This indicates that the idElementName is "columnIndex" - //! @return Return true if successful, false otherwise - bool GetData3DSizes( int64_t dataIndex, int64_t &rowMax, int64_t &columnMax, int64_t &pointsSize, - int64_t &groupsSize, int64_t &countSize, bool &columnIndex ) const; - - //! @brief This function reads the group data into the provided buffers. - //! @param [in] dataIndex This in the index into the images3D vector. Must be less than GetData3DCount(). - //! @param [in] groupCount size of each of the buffers given - //! @param [out] idElementValue pointer to the buffer holding indices index for this group - //! @param [out] startPointIndex pointer to the buffer holding Starting index in to the "points" data vector for - //! the groups - //! @param [out] pointCount pointer to the buffer holding size of the groups given - //! @return Return true if successful, false otherwise - bool ReadData3DGroupsData( int64_t dataIndex, int64_t groupCount, int64_t *idElementValue, + /// @brief Returns the size of the point data + /// @param [in] dataIndex This in the index into the images3D vector. Must be less than + /// GetData3DCount(). + /// @param [out] rowMax This is the maximum row size + /// @param [out] columnMax This is the maximum column size + /// @param [out] pointsSize This is the total number of point records + /// @param [out] groupsSize This is the total number of group records + /// @param [out] countSize This is the maximum point count per group + /// @param [out] columnIndex This indicates that the idElementName is "columnIndex" + /// @return Return true if successful, false otherwise + bool GetData3DSizes( int64_t dataIndex, int64_t &rowMax, int64_t &columnMax, + int64_t &pointsSize, int64_t &groupsSize, int64_t &countSize, + bool &columnIndex ) const; + + /// @brief Reads the group data into the provided buffers. + /// @param [in] dataIndex This in the index into the images3D vector. Must be less than + /// GetData3DCount(). + /// @param [in] groupCount size of each of the buffers given + /// @param [out] idElementValue pointer to the buffer holding indices index for this group + /// @param [out] startPointIndex pointer to the buffer holding Starting index in to the + /// "points" data vector for the groups + /// @param [out] pointCount pointer to the buffer holding size of the groups given + /// @return Return true if successful, false otherwise + bool ReadData3DGroupsData( int64_t dataIndex, size_t groupCount, int64_t *idElementValue, int64_t *startPointIndex, int64_t *pointCount ) const; - //! @brief Use this function to read the actual 3D data - //! @details All the non-NULL buffers in buffers have number of elements = pointCount. - //! Call the CompressedVectorReader::read() until all data is read. - //! @param [in] dataIndex data block index given by the NewData3D - //! @param [in] pointCount size of each element buffer. - //! @param [in] buffers pointers to user-provided buffers - //! @return vector reader setup to read the selected data into the provided buffers + /// @brief Use this to read the actual 3D data + /// @details All the non-NULL buffers in buffers have number of elements = pointCount. + /// Call the CompressedVectorReader::read() until all data is read. + /// @param [in] dataIndex data block index + /// @param [in] pointCount size of each element buffer. + /// @param [in] buffers pointers to user-provided buffers + /// @return vector reader setup to read the selected data into the provided buffers CompressedVectorReader SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData &buffers ) const; - - //! @brief Use this function to read the actual 3D data - //! @details All the non-NULL buffers in buffers have number of elements = pointCount. - //! Call the CompressedVectorReader::read() until all data is read. - //! @param [in] dataIndex data block index given by the NewData3D - //! @param [in] pointCount size of each element buffer. - //! @param [in] buffers pointers to user-provided buffers - //! @return vector reader setup to read the selected data into the provided buffers + const Data3DPointsFloat &buffers ) const; + + /// @overload CompressedVectorReader SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData_d &buffers ) const; + const Data3DPointsDouble &buffers ) const; - //!@} + ///@} - //! @name Foundation API file information - //!@{ + /// @name File information + ///@{ - //! @brief Returns the file raw E57Root Structure Node + /// @brief Returns the file raw E57Root Structure Node StructureNode GetRawE57Root() const; - //! @brief Returns the raw Data3D Vector Node + /// @brief Returns the raw Data3D Vector Node VectorNode GetRawData3D() const; - //! @brief Returns the raw Image2D Vector Node + /// @brief Returns the raw Image2D Vector Node VectorNode GetRawImages2D() const; - //! @brief Returns the ram ImageFile Node which is need to add enhancements + /// @brief Returns the ram ImageFile Node which is need to add enhancements ImageFile GetRawIMF() const; - //!@} + ///@} - //! @cond documentNonPublic The following isn't part of the API, and isn't - //! documented. + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. protected: friend class ReaderImpl; - E57_OBJECT_IMPLEMENTATION( Reader ) // Internal implementation details, not part of API, must be last in object - //! @endcond + E57_INTERNAL_ACCESS( Reader ) + + protected: + std::shared_ptr impl_; + /// @endcond }; // end Reader class } // end namespace e57 diff --git a/src/3rdParty/libE57Format/include/E57SimpleWriter.h b/src/3rdParty/libE57Format/include/E57SimpleWriter.h index 32c5a0a2a6716..d3d31c1a375cf 100644 --- a/src/3rdParty/libE57Format/include/E57SimpleWriter.h +++ b/src/3rdParty/libE57Format/include/E57SimpleWriter.h @@ -3,6 +3,7 @@ * * Copyright (c) 2010 Stan Coleby (scoleby@intelisum.com) * Copyright (c) 2020 PTC Inc. + * Copyright (c) 2022 Andy Maloney * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by @@ -29,109 +30,181 @@ #pragma once -//! @file E57SimpleWriter.h E57 Simple API for writing E57 +/// @file +/// @brief E57 Simple API for writing E57. +/// @details This includes support for the +/// [E57_EXT_surface_normals](http://www.libe57.org/E57_EXT_surface_normals.txt) extension. #include "E57SimpleData.h" namespace e57 { + /// Options to the Writer constructor + struct E57_DLL WriterOptions + { + /// Optional file guid + ustring guid; + + /// Information describing the Coordinate Reference System to be used for the file + ustring coordinateMetadata; + }; - //! @brief Used for writing of the E57 file with E57 Simple API + /// @brief Used for writing an E57 file using the E57 Simple API. + /// + /// The Writer includes support for the + /// [E57_EXT_surface_normals](http://www.libe57.org/E57_EXT_surface_normals.txt) extension. class E57_DLL Writer { public: - //! @brief This function is the constructor for the writer class - //! @param [in] filePath file path to E57 file - //! @param [in] coordinateMetaData Information describing the Coordinate Reference System to be used for the file - Writer( const ustring &filePath, const ustring &coordinateMetaData = {} ); - - //! @brief This function returns true if the file is open + /// @brief Writer constructor + /// @param [in] filePath Path to E57 file + /// @param [in] options Options to be used for the file + Writer( const ustring &filePath, const WriterOptions &options ); + + /// @brief Writer constructor (deprecated) + /// @param [in] filePath Path to E57 file + /// @param [in] coordinateMetadata Information describing the Coordinate Reference System to + /// be used for the file + /// @deprecated Will be removed in 4.0. Use Writer( const ustring &filePath, const + /// WriterOptions &options ) instead. + [[deprecated( + "Will be removed in 4.0. Use Writer( ustring, WriterOptions )." )]] // TODO Remove in 4.0 + explicit Writer( const ustring &filePath, const ustring &coordinateMetadata = {} ); + + /// @brief Returns true if the file is open bool IsOpen() const; - //! @brief This function closes the file + /// @brief Closes the file bool Close(); - //! @name Image2D - //!@{ - - //! @brief This function writes a new Image2D header - //! @details The user needs to config a Image2D structure with all the camera information before making this call. - //! @param [in,out] image2DHeader header metadata - //! @return Returns the image2D index - int64_t NewImage2D( Image2D &image2DHeader ); - - //! @brief This function writes the actual image data - //! @param [in] imageIndex picture block index given by the NewImage2D - //! @param [in] imageType identifies the image format desired. - //! @param [in] imageProjection identifies the projection desired. - //! @param [in] buffer pointer the buffer - //! @param [in] start position in the block to start writing - //! @param [in] count size of desired chuck or buffer size - //! @return Returns the number of bytes written - int64_t WriteImage2DData( int64_t imageIndex, Image2DType imageType, Image2DProjection imageProjection, - void *buffer, int64_t start, int64_t count ); - - //!@} - - //! @name Data3D - //!@{ - - //! @brief This function writes new Data3D header - //! @details The user needs to config a Data3D structure with all the scanning information before making this - //! call. - //! @param [in,out] data3DHeader scan metadata - //! @return Returns the index of the new scan's data3D block. - int64_t NewData3D( Data3D &data3DHeader ); - - //! @brief This function setups a writer to write the actual scan data - //! @param [in] dataIndex index returned by NewData3D - //! @param [in] pointCount Number of points to write (number of elements in each of the buffers) - //! @param [in] buffers pointers to user-provided buffers - //! @return returns a vector writer setup to write the selected scan data - CompressedVectorWriter SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData &buffers ); - - //! @brief This function setups a writer to write the actual scan data - //! @param [in] dataIndex index returned by NewData3D - //! @param [in] pointCount Number of points to write (number of elements in each of the buffers) - //! @param [in] buffers pointers to user-provided buffers - //! @return returns a vector writer setup to write the selected scan data - CompressedVectorWriter SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData_d &buffers ); - - //! @brief This function writes out the group data - //! @param [in] dataIndex data block index given by the NewData3D - //! @param [in] groupCount size of each of the buffers given - //! @param [in] buffer of idElementValue index for this group - //! @param [in] startPointIndex buffer with starting indices in to the "points" data vector for the groups - //! @param [in] pointCount buffer with sizes of the groups given - //! @return Return true if successful, false otherwise - bool WriteData3DGroupsData( int64_t dataIndex, int64_t groupCount, int64_t *idElementValue, + /// @name Image2D + ///@{ + + /// @brief This function writes the Image2D data to the file + /// @note @p image2DHeader may be modified (adding a guid or adding missing, required fields). + /// @param [in,out] image2DHeader header metadata + /// @param [in] imageType identifies the image format + /// @param [in] imageProjection identifies the projection + /// @param [in] startPos position in the block to start writing + /// @param [in] buffer pointer the data buffer + /// @param [in] byteCount buffer size + /// @return Returns the number of bytes written + int64_t WriteImage2DData( Image2D &image2DHeader, Image2DType imageType, + Image2DProjection imageProjection, int64_t startPos, void *buffer, + int64_t byteCount ); + + /// @brief Writes a new Image2D header + /// @details The user needs to config a Image2D structure with all the camera information + /// before making this call. + /// @param [in,out] image2DHeader header metadata + /// @return Returns the image2D index + /// @deprecated Will be removed in 4.0. Use WriteImage2DData(Image2D + /// &,Image2DType,Image2DProjection,int64_t,void + /// *,int64_t) instead. + [[deprecated( "Will be removed in 4.0. Use WriteImage2DData()." )]] // TODO Remove in 4.0 + int64_t + NewImage2D( Image2D &image2DHeader ); + + /// @brief Writes the actual image data + /// @param [in] imageIndex picture block index given by the NewImage2D + /// @param [in] imageType identifies the image format desired. + /// @param [in] imageProjection identifies the projection desired. + /// @param [in] buffer pointer the buffer + /// @param [in] start position in the block to start writing + /// @param [in] count size of desired chunk or buffer size + /// @return Returns the number of bytes written + /// @deprecated Will be removed in 4.0. Use WriteImage2DData(Image2D + /// &,Image2DType,Image2DProjection,int64_t,void + /// *,int64_t) instead. + [[deprecated( "Will be removed in 4.0. Use WriteImage2DData(Image2D " + "&,Image2DType,Image2DProjection,int64_t,void " + "*,int64_t)." )]] // TODO Remove in 4.0 + int64_t + WriteImage2DData( int64_t imageIndex, Image2DType imageType, + Image2DProjection imageProjection, void *buffer, int64_t start, + int64_t count ); + + ///@} + + /// @name Data3D + ///@{ + + /// @brief This function writes the Data3D data to the file + /// @details The user needs to config a Data3D structure with all the scanning information + /// before making this call. + /// @note @p data3DHeader may be modified (adding a guid or adding missing, required fields). + /// @param [in,out] data3DHeader metadata about what is included in the buffers + /// @param [in] buffers pointers to user-provided buffers containing the actual data + /// @return Returns the index of the new scan's data3D block. + int64_t WriteData3DData( Data3D &data3DHeader, const Data3DPointsFloat &buffers ); + + /// @overload + int64_t WriteData3DData( Data3D &data3DHeader, const Data3DPointsDouble &buffers ); + + /// @brief Writes a new Data3D header + /// @details The user needs to config a Data3D structure with all the scanning information + /// before making this call. + /// @param [in,out] data3DHeader scan metadata + /// @return Returns the index of the new scan's data3D block. + /// @deprecated Will be removed in 4.0. Use WriteData3DData() instead. + [[deprecated( "Will be removed in 4.0. Use WriteData3DData()." )]] // TODO Remove in 4.0 + int64_t + NewData3D( Data3D &data3DHeader ); + + /// @brief Sets up a writer to write the actual scan data + /// @param [in] dataIndex index returned by NewData3D + /// @param [in] pointCount Number of points to write (number of elements in each of the + /// buffers) + /// @param [in] buffers pointers to user-provided buffers + /// @return returns a vector writer setup to write the selected scan data + /// @deprecated Will be removed in 4.0. Use WriteData3DData() instead. + [[deprecated( "Will be removed in 4.0. Use WriteData3DData()." )]] // TODO Remove in 4.0 + CompressedVectorWriter + SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, + const Data3DPointsFloat &buffers ); + + /// @overload + [[deprecated( "Will be removed in 4.0. Use WriteData3DData()." )]] // TODO Remove in 4.0 + CompressedVectorWriter + SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, + const Data3DPointsDouble &buffers ); + + /// @brief Writes out the group data + /// @param [in] dataIndex data block index given by the NewData3D + /// @param [in] groupCount size of each of the buffers given + /// @param [in] idElementValue buffer with idElementValue indices for this group + /// @param [in] startPointIndex buffer with starting indices in to the "points" data vector + /// for the groups + /// @param [in] pointCount buffer with sizes of the groups given + /// @return Return true if successful, false otherwise + bool WriteData3DGroupsData( int64_t dataIndex, size_t groupCount, int64_t *idElementValue, int64_t *startPointIndex, int64_t *pointCount ); - //!@} + ///@} - //! @name Foundation API file information - //!@{ + /// @name File information + ///@{ - //! @brief This function returns the file raw E57Root Structure Node + /// @brief Returns the file raw E57Root Structure Node StructureNode GetRawE57Root(); - //! @brief This function returns the raw Data3D Vector Node + /// @brief Returns the raw Data3D Vector Node VectorNode GetRawData3D(); - //! @brief This function returns the raw Image2D Vector Node + /// @brief Returns the raw Image2D Vector Node VectorNode GetRawImages2D(); - //! @brief This function returns the ram ImageFile Node which is need to add enhancements + /// @brief Returns the ram ImageFile Node which is need to add enhancements ImageFile GetRawIMF(); - //!@} + ///@} - //! @cond documentNonPublic The following isn't part of the API, and isn't - //! documented. + /// @cond documentNonPublic The following isn't part of the API, and isn't documented. protected: friend class WriterImpl; - E57_OBJECT_IMPLEMENTATION( Writer ) // Internal implementation details, not part of API, must be last in object - //! @endcond + E57_INTERNAL_ACCESS( Writer ) + + protected: + std::shared_ptr impl_; + /// @endcond }; // end Writer class } // end namespace e57 diff --git a/src/3rdParty/libE57Format/include/E57Version.h b/src/3rdParty/libE57Format/include/E57Version.h new file mode 100644 index 0000000000000..20ac2d27565f1 --- /dev/null +++ b/src/3rdParty/libE57Format/include/E57Version.h @@ -0,0 +1,72 @@ +#pragma once +// Copyright Β© 2022 Andy Maloney +// SPDX-License-Identifier: MIT + +/// @file E57Version.h ASTM & libE57Format version information. + +#include + +#include "E57Export.h" + +namespace e57 +{ + namespace Version + { + /*! + @brief Get the version of the ASTM E57 standard that libE57Format supports. + + @returns The version as a string (e.g. "1.0") + */ + E57_DLL std::string astm(); + + /*! + @brief Get the major version of the ASTM E57 standard that libE57Format supports. + + @returns The major version + */ + E57_DLL uint32_t astmMajor(); + + /*! + @brief Get the minor version of the ASTM E57 standard that libE57Format supports. + + @returns The minor version + */ + E57_DLL uint32_t astmMinor(); + + /*! + @brief Get the version of libE57Format library. + + @returns The version as a string (e.g. "E57Format-3.0.0-x86_64-darwin-AppleClang140"). + */ + E57_DLL std::string library(); + + /*! + @brief Get the version of ASTM E57 standard that the API implementation supports, and library + id string. + + @param [out] astmMajor The major version number of the ASTM E57 standard supported. + @param [out] astmMinor The minor version number of the ASTM E57 standard supported. + @param [out] libraryId A string identifying the implementation of the API. + + @details + Since the E57 implementation may be dynamically linked underneath the API, the version string + for the implementation and the ASTM version that it supports can't be determined at + compile-time. This function returns these identifiers from the underlying implementation. + + @throw No E57Exceptions. + */ + E57_DLL void get( uint32_t &astmMajor, uint32_t &astmMinor, std::string &libraryId ); + } + + namespace Utilities + { + /*! + @copydetails Version::get() + @deprecated Will be removed in 4.0. Use Version::get() or other functions in the Version + namespace. + */ + [[deprecated( "Will be removed in 4.0. Use Version::get() or other functions in the Version " + "namespace." )]] E57_DLL void + getVersions( int &astmMajor, int &astmMinor, std::string &libraryId ); + } +} diff --git a/src/3rdParty/libE57Format/src/ASTMVersion.h b/src/3rdParty/libE57Format/src/ASTMVersion.h new file mode 100644 index 0000000000000..23d38ca09a36b --- /dev/null +++ b/src/3rdParty/libE57Format/src/ASTMVersion.h @@ -0,0 +1,16 @@ +#pragma once +// Copyright Β© 2022 Andy Maloney +// SPDX-License-Identifier: MIT + +#include + +namespace e57 +{ + /// The file format major version number. The value shall be 1. + /// @remark E57 Standard Table 1 - Format of the E57 File Header Section + constexpr uint32_t E57_FORMAT_MAJOR = 1; + + /// The file format minor version number. The value shall be 0. + /// @remark E57 Standard Table 1 - Format of the E57 File Header Section + constexpr uint32_t E57_FORMAT_MINOR = 0; +} diff --git a/src/3rdParty/libE57Format/src/BlobNode.cpp b/src/3rdParty/libE57Format/src/BlobNode.cpp new file mode 100644 index 0000000000000..54c6b740a3312 --- /dev/null +++ b/src/3rdParty/libE57Format/src/BlobNode.cpp @@ -0,0 +1,367 @@ +/* + * BlobNode.cpp - implementation of public functions of the BlobNode class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file BlobNode.cpp + +#include "BlobNodeImpl.h" +#include "StringFunctions.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/*! +@brief Check whether BlobNode class invariant is true +@copydetails IntegerNode::checkInvariant() +*/ +void BlobNode::checkInvariant( bool /*doRecurse*/, bool doUpcast ) const +{ + // If destImageFile not open, can't test invariant (almost every call would throw) + if ( !destImageFile().isOpen() ) + { + return; + } + + // If requested, call Node::checkInvariant + if ( doUpcast ) + { + static_cast( *this ).checkInvariant( false, false ); + } + + if ( byteCount() < 0 ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } +} + +/*! +@class e57::BlobNode + +@brief An E57 element encoding an fixed-length sequence of bytes with an opaque format. + +@details +A BlobNode is a terminal node (i.e. having no children) that holds an opaque, fixed-length sequence +of bytes. The number of bytes in the BlobNode is declared at creation time. The content of the blob +is stored within the E57 file in an efficient binary format (but not compressed). The BlobNode +cannot grow after it is created. There is no ordering constraints on how content of a BlobNode may +be accessed (i.e. it is random access). BlobNodes in an ImageFile opened for reading are read-only. + +There are two categories of BlobNodes, distinguished by their usage: private BlobNodes and public +BlobNodes. In a private BlobNode, the format of its content bytes is not published. This is useful +for storing proprietary data that a writer does not wish to share with all readers. Rather than put +this information in a separate file, the writer can embed the file inside the E57 file so it cannot +be lost. + +In a public BlobNode, the format is published or follows some industry standard format (e.g. JPEG). +Rather than reinvent the wheel in applications that are already well-served by an existing format +standard, an E57 file writer can just embed an existing file as an "attachment" in a BlobNode. The +internal format of a public BlobNode is not enforced by the Foundation API. It is recommended that +there be some mechanism for a reader to know ahead of time which format the BlobNode content adheres +to (either specified by a document, or encoded by some scheme in the E57 Element tree). + +The BlobNode is the one node type where the set-once policy is not strictly enforced. It is possible +to write the same byte location in a BlobNode several times. However it is not recommended. + +See Node class discussion for discussion of the common functions that StructureNode supports. + +@section BlobNode_invariant Class Invariant +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or, can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude BlobNode.cpp +@skip void BlobNode::checkInvariant +@until ^} + +@see Node +*/ + +/*! +@brief Create an element for storing a sequence of bytes with an opaque format. +@param [in] destImageFile The ImageFile where the new node will eventually be stored. +@param [in] byteCount The number of bytes reserved in the ImageFile for holding the blob. +@details +The BlobNode class corresponds to the ASTM E57 standard Blob element. + +See the class discussion at bottom of BlobNode page for more details. + +The E57 Foundation Implementation may pre-allocate disk space in the ImageFile to store the declared +length of the blob. The disk must have enough free space to store @a byteCount bytes of data. The +data of a newly created BlobNode is initialized to zero. + +The @a destImageFile indicates which ImageFile the BlobNode will eventually be attached to. A node +is attached to an ImageFile by adding it underneath the predefined root of the ImageFile (gotten +from ImageFile::root). It is not an error to fail to attach the BlobNode to the @a destImageFile. It +is an error to attempt to attach the BlobNode to a different ImageFile. + +@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be true). +@pre The @a destImageFile must have been opened in write mode (i.e. destImageFile.isWritable() +must be true). +@pre byteCount >= 0 + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorFileReadOnly +@throw ::ErrorInternal All objects in undocumented state + +@see Node, BlobNode::read, BlobNode::write +*/ +BlobNode::BlobNode( const ImageFile &destImageFile, int64_t byteCount ) : + impl_( new BlobNodeImpl( destImageFile.impl(), byteCount ) ) +{ +} + +/*! +@brief Is this a root node. +@copydetails Node::isRoot() +*/ +bool BlobNode::isRoot() const +{ + return impl_->isRoot(); +} + +/*! +@brief Return parent of node, or self if a root node. +@copydetails Node::parent() +*/ +Node BlobNode::parent() const +{ + return Node( impl_->parent() ); +} + +/*! +@brief Get absolute pathname of node. +@copydetails Node::pathName() +*/ +ustring BlobNode::pathName() const +{ + return impl_->pathName(); +} + +/*! +@brief Get elementName string, that identifies the node in its parent. +@copydetails Node::elementName() +*/ +ustring BlobNode::elementName() const +{ + return impl_->elementName(); +} + +/*! +@brief Get the ImageFile that was declared as the destination for the node when it was created. +@copydetails Node::destImageFile() +*/ +ImageFile BlobNode::destImageFile() const +{ + return ImageFile( impl_->destImageFile() ); +} + +/*! +@brief Has node been attached into the tree of an ImageFile. +@copydetails Node::isAttached() +*/ +bool BlobNode::isAttached() const +{ + return impl_->isAttached(); +} + +/*! +@brief Get size of blob declared when it was created. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The declared size of the blob when it was created. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see BlobNode::read, BlobNode::write +*/ +int64_t BlobNode::byteCount() const +{ + return impl_->byteCount(); +} + +/*! +@brief Read a buffer of bytes from a blob. + +@param [in] buf A memory buffer to store bytes read from the blob. +@param [in] start The index of the first byte in blob to read. +@param [in] count The number of bytes to read. + +@details +The memory buffer @a buf must be able to store at least @a count bytes. + +The data is stored in a binary section of the ImageFile with checksum protection, so undetected +corruption is very unlikely. It is an error to attempt to read outside the declared size of the +Blob. The format of the data read is opaque (unspecified by the ASTM E57 data format standard). +Since @a buf is a byte buffer, byte ordering is irrelevant (it will come out in the same order that +it went in). There is no constraint on the ordering of reads. Any part of the Blob data can be read +zero or more times. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@pre buf != NULL +@pre 0 <= @a start < byteCount() +@pre 0 <= count +@pre (@a start + @a count) < byteCount() + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorSeekFailed +@throw ::ErrorReadFailed +@throw ::ErrorBadChecksum +@throw ::ErrorInternal All objects in undocumented state + +@see BlobNode::byteCount, BlobNode::write +*/ +void BlobNode::read( uint8_t *buf, int64_t start, size_t count ) +{ + impl_->read( buf, start, count ); +} + +/*! +@brief Write a buffer of bytes to a blob. + +@param [in] buf A memory buffer of bytes to write to the blob. +@param [in] start The index of the first byte in blob to write to. +@param [in] count The number of bytes to write. + +@details +The memory buffer @a buf must store at least @a count bytes. + +The data is stored in a binary section of the ImageFile with checksum protection, so undetected +corruption is very unlikely. It is an error to attempt to write outside the declared size of the +Blob. The format of the data written is opaque (unspecified by the ASTM E57 data format standard). +Since @a buf is a byte buffer, byte ordering is irrelevant (it will come out in the same order that +it went in). There is no constraint on the ordering of writes. It is not an error to write a portion +of the BlobNode data more than once, or not at all. Initially all the BlobNode data is zero, so if a +portion is not written, it will remain zero. The BlobNode is one of the two node types that must be +attached to the root of a write mode ImageFile before write operations can be performed (the other +type is CompressedVectorNode). + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@pre The associated destImageFile must have been opened in write mode (i.e. +destImageFile().isWritable()). +@pre The BlobNode must be attached to an ImageFile (i.e. isAttached()). +@pre buf != NULL +@pre 0 <= @a start < byteCount() +@pre 0 <= count +@pre (@a start + @a count) < byteCount() + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorFileReadOnly +@throw ::ErrorNodeUnattached +@throw ::ErrorSeekFailed +@throw ::ErrorReadFailed +@throw ::ErrorWriteFailed +@throw ::ErrorBadChecksum +@throw ::ErrorInternal All objects in undocumented state + +@see BlobNode::byteCount, BlobNode::read +*/ +void BlobNode::write( uint8_t *buf, int64_t start, size_t count ) +{ + impl_->write( buf, start, count ); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void BlobNode::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void BlobNode::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif + +/*! +@brief Upcast a BlobNode handle to a generic Node handle. + +@details +An upcast is always safe, and the compiler can automatically insert it for initializations of Node +variables and Node function arguments. + +@return A smart Node handle referencing the underlying object. + +@throw No E57Exceptions. + +@see Explanation in Node, Node::type(), BlobNode(const Node&) +*/ +BlobNode::operator Node() const +{ + // Upcast from shared_ptr to SharedNodeImplPtr and construct + // a Node object + return Node( impl_ ); +} + +/*! +@brief Downcast a generic Node handle to a BlobNode handle. + +@param [in] n The generic handle to downcast. + +@details +The handle @a n must be for an underlying BlobNode, otherwise an exception is thrown. In designs +that need to avoid the exception, use Node::type() to determine the actual type of the @a n before +downcasting. This function must be explicitly called (c++ compiler cannot insert it automatically). + +@throw ::ErrorBadNodeDowncast + +@see Node::type(), BlobNode::operator Node() +*/ +BlobNode::BlobNode( const Node &n ) +{ + if ( n.type() != TypeBlob ) + { + throw E57_EXCEPTION2( ErrorBadNodeDowncast, "nodeType=" + toString( n.type() ) ); + } + + // Set our shared_ptr to the downcast shared_ptr + impl_ = std::static_pointer_cast( n.impl() ); +} + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +BlobNode::BlobNode( const ImageFile &destImageFile, int64_t fileOffset, int64_t length ) : + impl_( new BlobNodeImpl( destImageFile.impl(), fileOffset, length ) ) +{ +} + +BlobNode::BlobNode( std::shared_ptr ni ) : impl_( ni ) +{ +} +/// @endcond diff --git a/src/3rdParty/libE57Format/src/BlobNodeImpl.cpp b/src/3rdParty/libE57Format/src/BlobNodeImpl.cpp index e3187310d6996..34783ed9cf308 100644 --- a/src/3rdParty/libE57Format/src/BlobNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/BlobNodeImpl.cpp @@ -29,19 +29,21 @@ #include "CheckedFile.h" #include "ImageFileImpl.h" #include "SectionHeaders.h" +#include "StringFunctions.h" namespace e57 { - BlobNodeImpl::BlobNodeImpl( ImageFileImplWeakPtr destImageFile, int64_t byteCount ) : NodeImpl( destImageFile ) + BlobNodeImpl::BlobNodeImpl( ImageFileImplWeakPtr destImageFile, int64_t byteCount ) : + NodeImpl( destImageFile ) { // don't checkImageFileOpen, NodeImpl() will do it ImageFileImplSharedPtr imf( destImageFile ); - /// This what caller thinks blob length is + // This what caller thinks blob length is blobLogicalLength_ = byteCount; - /// Round segment length up to multiple of 4 bytes + // Round segment length up to multiple of 4 bytes binarySectionLogicalLength_ = sizeof( BlobSectionHeader ) + blobLogicalLength_; unsigned remainder = binarySectionLogicalLength_ % 4; if ( remainder > 0 ) @@ -49,32 +51,33 @@ namespace e57 binarySectionLogicalLength_ += 4 - remainder; } - /// Reserve space for blob in file, extend with zeros since writes will - /// happen at later time by caller + // Reserve space for blob in file, extend with zeros since writes will + // happen at later time by caller binarySectionLogicalStart_ = imf->allocateSpace( binarySectionLogicalLength_, true ); - /// Prepare BlobSectionHeader + // Prepare BlobSectionHeader BlobSectionHeader header; header.sectionLogicalLength = binarySectionLogicalLength_; -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE header.dump(); //??? #endif - /// Write header at beginning of section + // Write header at beginning of section imf->file_->seek( binarySectionLogicalStart_ ); imf->file_->write( reinterpret_cast( &header ), sizeof( header ) ); } - BlobNodeImpl::BlobNodeImpl( ImageFileImplWeakPtr destImageFile, int64_t fileOffset, int64_t length ) : + BlobNodeImpl::BlobNodeImpl( ImageFileImplWeakPtr destImageFile, int64_t fileOffset, + int64_t length ) : NodeImpl( destImageFile ) { - /// Init blob object that already exists in E57 file currently reading. + // Init blob object that already exists in E57 file currently reading. // don't checkImageFileOpen, NodeImpl() will do it ImageFileImplSharedPtr imf( destImageFile ); - /// Init state from values read from XML + // Init state from values read from XML blobLogicalLength_ = length; binarySectionLogicalStart_ = imf->file_->physicalToLogical( fileOffset ); binarySectionLogicalLength_ = sizeof( BlobSectionHeader ) + blobLogicalLength_; @@ -84,24 +87,24 @@ namespace e57 { // don't checkImageFileOpen, NodeImpl() will do it - /// Same node type? - if ( ni->type() != E57_BLOB ) + // Same node type? + if ( ni->type() != TypeBlob ) { return ( false ); } - /// Downcast to shared_ptr + // Downcast to shared_ptr std::shared_ptr bi( std::static_pointer_cast( ni ) ); - /// blob lengths must match + // blob lengths must match if ( blobLogicalLength_ != bi->blobLogicalLength_ ) { return ( false ); } - /// ignore blob contents, doesn't have to match + // ignore blob contents, doesn't have to match - /// Types match + // Types match return ( true ); } @@ -109,7 +112,7 @@ namespace e57 { // don't checkImageFileOpen, NodeImpl() will do it - /// We have no sub-structure, so if path not empty return false + // We have no sub-structure, so if path not empty return false return pathName.empty(); } @@ -126,9 +129,10 @@ namespace e57 checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); if ( static_cast( start ) + count > blobLogicalLength_ ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_API_ARGUMENT, - "this->pathName=" + this->pathName() + " start=" + toString( start ) + - " count=" + toString( count ) + " length=" + toString( blobLogicalLength_ ) ); + throw E57_EXCEPTION2( ErrorBadAPIArgument, + "this->pathName=" + this->pathName() + + " start=" + toString( start ) + " count=" + toString( count ) + + " length=" + toString( blobLogicalLength_ ) ); } ImageFileImplSharedPtr imf( destImageFile_ ); @@ -146,18 +150,19 @@ namespace e57 if ( !destImageFile->isWriter() ) { - throw E57_EXCEPTION2( E57_ERROR_FILE_IS_READ_ONLY, "fileName=" + destImageFile->fileName() ); + throw E57_EXCEPTION2( ErrorFileReadOnly, "fileName=" + destImageFile->fileName() ); } if ( !isAttached() ) { - throw E57_EXCEPTION2( E57_ERROR_NODE_UNATTACHED, "fileName=" + destImageFile->fileName() ); + throw E57_EXCEPTION2( ErrorNodeUnattached, "fileName=" + destImageFile->fileName() ); } if ( static_cast( start ) + count > blobLogicalLength_ ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_API_ARGUMENT, - "this->pathName=" + this->pathName() + " start=" + toString( start ) + - " count=" + toString( count ) + " length=" + toString( blobLogicalLength_ ) ); + throw E57_EXCEPTION2( ErrorBadAPIArgument, + "this->pathName=" + this->pathName() + + " start=" + toString( start ) + " count=" + toString( count ) + + " length=" + toString( blobLogicalLength_ ) ); } ImageFileImplSharedPtr imf( destImageFile_ ); @@ -170,11 +175,11 @@ namespace e57 { // don't checkImageFileOpen - /// We are a leaf node, so verify that we are listed in set. ???true for - /// blobs? what exception get if try blob in compressedvector? + // We are a leaf node, so verify that we are listed in set. ???true for + // blobs? what exception get if try blob in compressedvector? if ( pathNames.find( relativePathName( origin ) ) == pathNames.end() ) { - throw E57_EXCEPTION2( E57_ERROR_NO_BUFFER_FOR_ELEMENT, "this->pathName=" + this->pathName() ); + throw E57_EXCEPTION2( ErrorNoBufferForElement, "this->pathName=" + this->pathName() ); } } @@ -184,7 +189,7 @@ namespace e57 // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName ) + if ( forcedFieldName != nullptr ) { fieldName = forcedFieldName; } @@ -197,11 +202,11 @@ namespace e57 //??? Type --> type //??? need to have length?, check same as in section header? uint64_t physicalOffset = cf.logicalToPhysical( binarySectionLogicalStart_ ); - cf << space( indent ) << "<" << fieldName << " type=\"Blob\" fileOffset=\"" << physicalOffset << "\" length=\"" - << blobLogicalLength_ << "\"/>\n"; + cf << space( indent ) << "<" << fieldName << " type=\"Blob\" fileOffset=\"" << physicalOffset + << "\" length=\"" << blobLogicalLength_ << "\"/>\n"; } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void BlobNodeImpl::dump( int indent, std::ostream &os ) const { // don't checkImageFileOpen @@ -209,8 +214,10 @@ namespace e57 << " (" << type() << ")" << std::endl; NodeImpl::dump( indent, os ); os << space( indent ) << "blobLogicalLength_: " << blobLogicalLength_ << std::endl; - os << space( indent ) << "binarySectionLogicalStart: " << binarySectionLogicalStart_ << std::endl; - os << space( indent ) << "binarySectionLogicalLength: " << binarySectionLogicalLength_ << std::endl; + os << space( indent ) << "binarySectionLogicalStart: " << binarySectionLogicalStart_ + << std::endl; + os << space( indent ) << "binarySectionLogicalLength: " << binarySectionLogicalLength_ + << std::endl; // size_t i; // for (i = 0; i < blobLogicalLength_ && i < 10; i++) { // uint8_t b; diff --git a/src/3rdParty/libE57Format/src/BlobNodeImpl.h b/src/3rdParty/libE57Format/src/BlobNodeImpl.h index 8364d9fb0a112..452577ddcd48a 100644 --- a/src/3rdParty/libE57Format/src/BlobNodeImpl.h +++ b/src/3rdParty/libE57Format/src/BlobNodeImpl.h @@ -39,8 +39,9 @@ namespace e57 NodeType type() const override { - return E57_BLOB; + return TypeBlob; } + bool isTypeEquivalent( NodeImplSharedPtr ni ) override; bool isDefined( const ustring &pathName ) override; @@ -53,7 +54,7 @@ namespace e57 void writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, const char *forcedFieldName = nullptr ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif diff --git a/src/3rdParty/libE57Format/src/CMakeLists.txt b/src/3rdParty/libE57Format/src/CMakeLists.txt index b9b8d2bb166e4..1776177342492 100644 --- a/src/3rdParty/libE57Format/src/CMakeLists.txt +++ b/src/3rdParty/libE57Format/src/CMakeLists.txt @@ -3,58 +3,73 @@ target_sources( E57Format PRIVATE - ${CMAKE_CURRENT_LIST_DIR}/BlobNodeImpl.h - ${CMAKE_CURRENT_LIST_DIR}/BlobNodeImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/CheckedFile.h - ${CMAKE_CURRENT_LIST_DIR}/CheckedFile.cpp - ${CMAKE_CURRENT_LIST_DIR}/Common.h - ${CMAKE_CURRENT_LIST_DIR}/Common.cpp - ${CMAKE_CURRENT_LIST_DIR}/CompressedVectorNodeImpl.h - ${CMAKE_CURRENT_LIST_DIR}/CompressedVectorNodeImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/CompressedVectorReaderImpl.h - ${CMAKE_CURRENT_LIST_DIR}/CompressedVectorReaderImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/CompressedVectorWriterImpl.h - ${CMAKE_CURRENT_LIST_DIR}/CompressedVectorWriterImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/DecodeChannel.h - ${CMAKE_CURRENT_LIST_DIR}/DecodeChannel.cpp - ${CMAKE_CURRENT_LIST_DIR}/Decoder.h - ${CMAKE_CURRENT_LIST_DIR}/Decoder.cpp - ${CMAKE_CURRENT_LIST_DIR}/Encoder.h - ${CMAKE_CURRENT_LIST_DIR}/Encoder.cpp - ${CMAKE_CURRENT_LIST_DIR}/FloatNodeImpl.h - ${CMAKE_CURRENT_LIST_DIR}/FloatNodeImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/IntegerNodeImpl.h - ${CMAKE_CURRENT_LIST_DIR}/IntegerNodeImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/NodeImpl.h - ${CMAKE_CURRENT_LIST_DIR}/NodeImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/Packet.h - ${CMAKE_CURRENT_LIST_DIR}/Packet.cpp - ${CMAKE_CURRENT_LIST_DIR}/ImageFileImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/ImageFileImpl.h - ${CMAKE_CURRENT_LIST_DIR}/ReaderImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/ReaderImpl.h - ${CMAKE_CURRENT_LIST_DIR}/ScaledIntegerNodeImpl.h - ${CMAKE_CURRENT_LIST_DIR}/ScaledIntegerNodeImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/SectionHeaders.h - ${CMAKE_CURRENT_LIST_DIR}/SectionHeaders.cpp - ${CMAKE_CURRENT_LIST_DIR}/SourceDestBufferImpl.h - ${CMAKE_CURRENT_LIST_DIR}/SourceDestBufferImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/StringNodeImpl.h - ${CMAKE_CURRENT_LIST_DIR}/StringNodeImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/StructureNodeImpl.h - ${CMAKE_CURRENT_LIST_DIR}/StructureNodeImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/VectorNodeImpl.h - ${CMAKE_CURRENT_LIST_DIR}/VectorNodeImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/WriterImpl.cpp - ${CMAKE_CURRENT_LIST_DIR}/WriterImpl.h - ${CMAKE_CURRENT_LIST_DIR}/E57Exception.cpp - ${CMAKE_CURRENT_LIST_DIR}/E57Format.cpp - ${CMAKE_CURRENT_LIST_DIR}/E57SimpleData.cpp - ${CMAKE_CURRENT_LIST_DIR}/E57SimpleReader.cpp - ${CMAKE_CURRENT_LIST_DIR}/E57SimpleWriter.cpp - ${CMAKE_CURRENT_LIST_DIR}/E57Version.h - ${CMAKE_CURRENT_LIST_DIR}/E57XmlParser.cpp - ${CMAKE_CURRENT_LIST_DIR}/E57XmlParser.h + ASTMVersion.h + BlobNode.cpp + BlobNodeImpl.h + BlobNodeImpl.cpp + CheckedFile.h + CheckedFile.cpp + Common.h + Common.cpp + CompressedVectorNode.cpp + CompressedVectorNodeImpl.h + CompressedVectorNodeImpl.cpp + CompressedVectorReader.cpp + CompressedVectorReaderImpl.h + CompressedVectorReaderImpl.cpp + CompressedVectorWriter.cpp + CompressedVectorWriterImpl.h + CompressedVectorWriterImpl.cpp + DecodeChannel.h + DecodeChannel.cpp + Decoder.h + Decoder.cpp + Encoder.h + Encoder.cpp + FloatNode.cpp + FloatNodeImpl.h + FloatNodeImpl.cpp + ImageFile.cpp + ImageFileImpl.h + ImageFileImpl.cpp + IntegerNode.cpp + IntegerNodeImpl.h + IntegerNodeImpl.cpp + Node.cpp + NodeImpl.h + NodeImpl.cpp + Packet.h + Packet.cpp + ReaderImpl.h + ReaderImpl.cpp + ScaledIntegerNode.cpp + ScaledIntegerNodeImpl.h + ScaledIntegerNodeImpl.cpp + SectionHeaders.h + SectionHeaders.cpp + SourceDestBuffer.cpp + SourceDestBufferImpl.h + SourceDestBufferImpl.cpp + StringNode.cpp + StringFunctions.h + StringFunctions.cpp + StringNodeImpl.h + StringNodeImpl.cpp + StructureNode.cpp + StructureNodeImpl.h + StructureNodeImpl.cpp + VectorNode.cpp + VectorNodeImpl.h + VectorNodeImpl.cpp + WriterImpl.h + WriterImpl.cpp + E57Exception.cpp + E57SimpleData.cpp + E57SimpleReader.cpp + E57SimpleWriter.cpp + E57Version.cpp + E57XmlParser.cpp + E57XmlParser.h ) target_include_directories( E57Format diff --git a/src/3rdParty/libE57Format/src/CheckedFile.cpp b/src/3rdParty/libE57Format/src/CheckedFile.cpp index 17f646d0a93d8..876a6b901e718 100644 --- a/src/3rdParty/libE57Format/src/CheckedFile.cpp +++ b/src/3rdParty/libE57Format/src/CheckedFile.cpp @@ -1,794 +1,785 @@ -/* - * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) - * Modified work Copyright 2018 - 2020 Andy Maloney - * - * Permission is hereby granted, free of charge, to any person or organization - * obtaining a copy of the software and accompanying documentation covered by - * this license (the "Software") to use, reproduce, display, distribute, - * execute, and transmit the Software, and to prepare derivative works of the - * Software, and to permit third-parties to whom the Software is furnished to - * do so, all subject to the following: - * - * The copyright notices in the Software and this entire statement, including - * the above license grant, this restriction and the following disclaimer, - * must be included in all copies of the Software, in whole or in part, and - * all derivative works of the Software, unless such copies or derivative - * works are solely in the form of machine-executable object code generated by - * a source language processor. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT - * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE - * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - */ - -#if defined( _WIN32 ) -#if defined( _MSC_VER ) -#include -#include -#elif defined( __GNUC__ ) -#define _LARGEFILE64_SOURCE -#define __LARGE64_FILES -#include -#include -#include -#else -#error "no supported compiler defined" -#endif -#elif defined( __linux__ ) -#define _LARGEFILE64_SOURCE -#define __LARGE64_FILES -#include -#include -#include -#elif defined( __APPLE__ ) -#include -#include -#else -#error "no supported OS platform defined" -#endif - -#include -#include -#include -#include - -#include "CRC.h" - -#include "CheckedFile.h" - -//#define E57_CHECK_FILE_DEBUG -#ifdef E57_CHECK_FILE_DEBUG -#include -#endif - -#ifndef O_BINARY -constexpr int O_BINARY = 0; -#endif - -using namespace e57; - -// These extra definitions are required in C++11. -// In C++17, "static constexpr" is implicitly inline, so these are not required. -constexpr size_t CheckedFile::physicalPageSizeLog2; -constexpr size_t CheckedFile::physicalPageSize; -constexpr uint64_t CheckedFile::physicalPageSizeMask; -constexpr size_t CheckedFile::logicalPageSize; - -/// Tool class to read buffer efficiently without -/// multiplying copy operations. -/// -/// WARNING: pointer input is handled by user! -class e57::BufferView -{ -public: - /// @param[IN] input: filled buffer owned by caller. - /// @param[IN] size: size of input - BufferView( const char *input, uint64_t size ) : streamSize_( size ), stream_( input ) - { - } - - uint64_t pos() const - { - return cursorStream_; - } - - bool seek( uint64_t offset, int whence ) - { - if ( whence == SEEK_CUR ) - { - cursorStream_ += offset; - } - else if ( whence == SEEK_SET ) - { - cursorStream_ = offset; - } - else if ( whence == SEEK_END ) - { - cursorStream_ = streamSize_ - offset; - } - - if ( cursorStream_ > streamSize_ ) - { - cursorStream_ = streamSize_; - return false; - } - - return true; - } - - void read( char *buffer, uint64_t count ) - { - const uint64_t start = cursorStream_; - for ( uint64_t i = 0; i < count; ++i ) - { - buffer[i] = stream_[start + i]; - ++cursorStream_; - } - } - -private: - const uint64_t streamSize_; - uint64_t cursorStream_ = 0; - const char *stream_; -}; - -CheckedFile::CheckedFile( const ustring &fileName, Mode mode, ReadChecksumPolicy policy ) : - fileName_( fileName ), checkSumPolicy_( policy ) -{ - switch ( mode ) - { - case ReadOnly: - fd_ = open64( fileName_, O_RDONLY | O_BINARY, 0 ); - - readOnly_ = true; - - physicalLength_ = lseek64( 0LL, SEEK_END ); - lseek64( 0, SEEK_SET ); - - logicalLength_ = physicalToLogical( physicalLength_ ); - break; - - case WriteCreate: - /// File truncated to zero length if already exists - fd_ = open64( fileName_, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, S_IWRITE | S_IREAD ); - break; - - case WriteExisting: - fd_ = open64( fileName_, O_RDWR | O_BINARY, 0 ); - - logicalLength_ = physicalToLogical( length( Physical ) ); //??? - break; - } -} - -CheckedFile::CheckedFile( const char *input, uint64_t size, ReadChecksumPolicy policy ) : - fileName_( "" ), checkSumPolicy_( policy ) -{ - bufView_ = new BufferView( input, size ); - - readOnly_ = true; - - physicalLength_ = lseek64( 0LL, SEEK_END ); - lseek64( 0, SEEK_SET ); - - logicalLength_ = physicalToLogical( physicalLength_ ); -} - -int CheckedFile::open64( const ustring &fileName, int flags, int mode ) -{ -#if defined( _MSC_VER ) - // Handle UTF-8 file names - Windows requires conversion to UTF-16 - std::wstring_convert> converter; - std::wstring widePath = converter.from_bytes( fileName ); - - int handle; - int err = _wsopen_s( &handle, widePath.c_str(), flags, _SH_DENYNO, mode ); - if ( handle < 0 ) - { - throw E57_EXCEPTION2( E57_ERROR_OPEN_FAILED, "err=" + toString( err ) + " fileName=" + fileName + - " flags=" + toString( flags ) + " mode=" + toString( mode ) ); - } - return handle; -#elif defined( __GNUC__ ) - int result = ::open( fileName_.c_str(), flags, mode ); - if ( result < 0 ) - { - throw E57_EXCEPTION2( E57_ERROR_OPEN_FAILED, "result=" + toString( result ) + " fileName=" + fileName + - " flags=" + toString( flags ) + " mode=" + toString( mode ) ); - } - return result; -#else -#error "no supported compiler defined" -#endif -} - -CheckedFile::~CheckedFile() -{ - try - { - close(); ///??? what if already closed? - } - catch ( ... ) - { - //??? report? - } -} - -void CheckedFile::read( char *buf, size_t nRead, size_t /*bufSize*/ ) -{ - //??? what if read past logical end?, or physical end? - //??? need to keep track of logical length? - //??? check bufSize OK - - const uint64_t end = position( Logical ) + nRead; - const uint64_t logicalLength = length( Logical ); - - if ( end > logicalLength ) - { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "fileName=" + fileName_ + " end=" + toString( end ) + - " length=" + toString( logicalLength ) ); - } - - uint64_t page = 0; - size_t pageOffset = 0; - - getCurrentPageAndOffset( page, pageOffset ); - - size_t n = std::min( nRead, logicalPageSize - pageOffset ); - - /// Allocate temp page buffer - std::vector page_buffer_v( physicalPageSize ); - char *page_buffer = &page_buffer_v[0]; - - const auto checksumMod = static_cast( std::nearbyint( 100.0 / checkSumPolicy_ ) ); - - while ( nRead > 0 ) - { - readPhysicalPage( page_buffer, page ); - - switch ( checkSumPolicy_ ) - { - case CHECKSUM_POLICY_NONE: - break; - - case CHECKSUM_POLICY_ALL: - verifyChecksum( page_buffer, page ); - break; - - default: - if ( !( page % checksumMod ) || ( nRead < physicalPageSize ) ) - { - verifyChecksum( page_buffer, page ); - } - break; - } - - memcpy( buf, page_buffer + pageOffset, n ); - - buf += n; - nRead -= n; - pageOffset = 0; - ++page; - - n = std::min( nRead, logicalPageSize ); - } - - /// When done, leave cursor just past end of last byte read - seek( end, Logical ); -} - -void CheckedFile::write( const char *buf, size_t nWrite ) -{ -#ifdef E57_MAX_VERBOSE - // cout << "write nWrite=" << nWrite << " position()="<< position() << std::endl; - // //??? -#endif - if ( readOnly_ ) - { - throw E57_EXCEPTION2( E57_ERROR_FILE_IS_READ_ONLY, "fileName=" + fileName_ ); - } - - uint64_t end = position( Logical ) + nWrite; - - uint64_t page = 0; - size_t pageOffset = 0; - - getCurrentPageAndOffset( page, pageOffset ); - - size_t n = std::min( nWrite, logicalPageSize - pageOffset ); - - /// Allocate temp page buffer - std::vector page_buffer_v( physicalPageSize ); - char *page_buffer = &page_buffer_v[0]; - - while ( nWrite > 0 ) - { - const uint64_t physicalLength = length( Physical ); - - if ( page * physicalPageSize < physicalLength ) - { - readPhysicalPage( page_buffer, page ); - } - -#ifdef E57_MAX_VERBOSE - // cout << " page_buffer[0] read: '" << page_buffer[0] << "'" << std::endl; - // cout << "copy " << n << "bytes to page=" << page << " pageOffset=" << - // pageOffset << " buf='"; //??? for (size_t i=0; i < n; i++) cout << - // buf[i]; cout << "'" << std::endl; -#endif - memcpy( page_buffer + pageOffset, buf, n ); - writePhysicalPage( page_buffer, page ); -#ifdef E57_MAX_VERBOSE - // cout << " page_buffer[0] after write: '" << page_buffer[0] << "'" << - // std::endl; //??? -#endif - buf += n; - nWrite -= n; - pageOffset = 0; - page++; - n = std::min( nWrite, logicalPageSize ); - } - - if ( end > logicalLength_ ) - { - logicalLength_ = end; - } - - /// When done, leave cursor just past end of buf - seek( end, Logical ); -} - -CheckedFile &CheckedFile::operator<<( const ustring &s ) -{ - write( s.c_str(), s.length() ); //??? should be times size of uchar? - return ( *this ); -} - -CheckedFile &CheckedFile::operator<<( int64_t i ) -{ - std::stringstream ss; - ss << i; - return ( *this << ss.str() ); -} - -CheckedFile &CheckedFile::operator<<( uint64_t i ) -{ - std::stringstream ss; - ss << i; - return ( *this << ss.str() ); -} - -CheckedFile &CheckedFile::operator<<( float f ) -{ - //??? is 7 digits right number? - return writeFloatingPoint( f, 7 ); -} - -CheckedFile &CheckedFile::operator<<( double d ) -{ - //??? is 17 digits right number? - return writeFloatingPoint( d, 17 ); -} - -template CheckedFile &CheckedFile::writeFloatingPoint( FTYPE value, int precision ) -{ -#ifdef E57_MAX_VERBOSE - std::cout << "CheckedFile::writeFloatingPoint, value=" << value << " precision=" << precision << std::endl; -#endif - - std::stringstream ss; - ss << std::scientific << std::setprecision( precision ) << value; - - /// Try to remove trailing zeroes and decimal point - /// E.g. 1.23456000000000000e+005 ==> 1.23456e+005 - /// E.g. 2.00000000000000000e+005 ==> 2e+005 - - ustring s = ss.str(); - const size_t len = s.length(); - -#ifdef E57_MAX_DEBUG - ustring old_s = s; -#endif - - /// Split into mantissa and exponent - /// E.g. 1.23456000000000000e+005 ==> "1.23456000000000000" + "e+005" - ustring mantissa = s.substr( 0, len - 5 ); - ustring exponent = s.substr( len - 5, 5 ); - - /// Double check that we understand the formatting - if ( exponent[0] == 'e' ) - { - /// Trim of any trailing zeros in mantissa - while ( mantissa[mantissa.length() - 1] == '0' ) - { - mantissa = mantissa.substr( 0, mantissa.length() - 1 ); - } - - /// Make one attempt to trim off trailing decimal point - if ( mantissa[mantissa.length() - 1] == '.' ) - { - mantissa = mantissa.substr( 0, mantissa.length() - 1 ); - } - - /// Reassemble whole floating point number - /// Check if can drop exponent. - if ( exponent == "e+000" ) - { - s = mantissa; - } - else - { - s = mantissa + exponent; - } - } - - // Disable these checks because they compare floats using "!=" which is - // invalid -#if 0 // E57_MAX_DEBUG - /// Double check same value - FTYPE old_value = static_cast(atof(old_s.c_str())); - FTYPE new_value = static_cast(atof(s.c_str())); - if (old_value != new_value) - throw E57_EXCEPTION2(E57_ERROR_INTERNAL, "fileName=" + fileName_ + " oldValue=" + toString(old_value) + " newValue=" + toString(new_value)); - if (new_value != value) - throw E57_EXCEPTION2(E57_ERROR_INTERNAL, "fileName=" + fileName_ + " newValue=" + toString(new_value) + " value=" + toString(value)); -#endif - - return ( *this << s ); -} - -void CheckedFile::seek( uint64_t offset, OffsetMode omode ) -{ - //??? check for seek beyond logicalLength_ - const auto pos = static_cast( omode == Physical ? offset : logicalToPhysical( offset ) ); - -#ifdef E57_MAX_VERBOSE - // cout << "seek offset=" << offset << " omode=" << omode << " pos=" << pos - // << std::endl; //??? -#endif - lseek64( pos, SEEK_SET ); -} - -uint64_t CheckedFile::lseek64( int64_t offset, int whence ) -{ - if ( ( fd_ < 0 ) && bufView_ ) - { - const auto uoffset = static_cast( offset ); - - if ( bufView_->seek( uoffset, whence ) ) - { - return bufView_->pos(); - } - - throw E57_EXCEPTION2( E57_ERROR_LSEEK_FAILED, "fileName=" + fileName_ + " offset=" + toString( offset ) + - " whence=" + toString( whence ) ); - } - -#if defined( _WIN32 ) -#if defined( _MSC_VER ) || defined( __MINGW32__ ) // mingw _is_ WIN32! - __int64 result = _lseeki64( fd_, offset, whence ); -#elif defined( __GNUC__ ) // this most likely will not get - // triggered (cygwin != WIN32)? -#ifdef E57_MAX_DEBUG - if ( sizeof( off_t ) != sizeof( offset ) ) - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "sizeof(off_t)=" + toString( sizeof( off_t ) ) ); -#endif - int64_t result = ::lseek( fd_, offset, whence ); -#else -#error "no supported compiler defined" -#endif -#elif defined( __linux__ ) - int64_t result = ::lseek64( fd_, offset, whence ); -#elif defined( __APPLE__ ) - int64_t result = ::lseek( fd_, offset, whence ); -#else -#error "no supported OS platform defined" -#endif - - if ( result < 0 ) - { - throw E57_EXCEPTION2( E57_ERROR_LSEEK_FAILED, "fileName=" + fileName_ + " offset=" + toString( offset ) + - " whence=" + toString( whence ) + - " result=" + toString( result ) ); - } - - return static_cast( result ); -} - -uint64_t CheckedFile::position( OffsetMode omode ) -{ - /// Get current file cursor position - const uint64_t pos = lseek64( 0LL, SEEK_CUR ); - - if ( omode == Physical ) - { - return pos; - } - - return physicalToLogical( pos ); -} - -uint64_t CheckedFile::length( OffsetMode omode ) -{ - if ( omode == Physical ) - { - if ( readOnly_ ) - { - return physicalLength_; - } - - // Current file position - uint64_t original_pos = lseek64( 0LL, SEEK_CUR ); - - // End file position - uint64_t end_pos = lseek64( 0LL, SEEK_END ); - - // Restore original position - lseek64( original_pos, SEEK_SET ); - - return end_pos; - } - - return logicalLength_; -} - -void CheckedFile::extend( uint64_t newLength, OffsetMode omode ) -{ -#ifdef E57_MAX_VERBOSE - // cout << "extend newLength=" << newLength << " omode="<< omode << std::endl; - // //??? -#endif - if ( readOnly_ ) - { - throw E57_EXCEPTION2( E57_ERROR_FILE_IS_READ_ONLY, "fileName=" + fileName_ ); - } - - uint64_t newLogicalLength = 0; - - if ( omode == Physical ) - { - newLogicalLength = physicalToLogical( newLength ); - } - else - { - newLogicalLength = newLength; - } - - uint64_t currentLogicalLength = length( Logical ); - - /// Make sure we are trying to make file longer - if ( newLogicalLength < currentLogicalLength ) - { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "fileName=" + fileName_ + " newLength=" + toString( newLogicalLength ) + - " currentLength=" + toString( currentLogicalLength ) ); - } - - /// Calc how may zero bytes we have to add to end - uint64_t nWrite = newLogicalLength - currentLogicalLength; - - /// Seek to current end of file - seek( currentLogicalLength, Logical ); - - uint64_t page = 0; - size_t pageOffset = 0; - - getCurrentPageAndOffset( page, pageOffset ); - - /// Calc first write size (may be partial page) - /// Watch out for different int sizes here. - size_t n = 0; - - if ( nWrite < logicalPageSize - pageOffset ) - { - n = static_cast( nWrite ); - } - else - { - n = logicalPageSize - pageOffset; - } - - /// Allocate temp page buffer - std::vector page_buffer_v( physicalPageSize ); - char *page_buffer = &page_buffer_v[0]; - - while ( nWrite > 0 ) - { - const uint64_t physicalLength = length( Physical ); - - if ( page * physicalPageSize < physicalLength ) - { - readPhysicalPage( page_buffer, page ); - } - -#ifdef E57_MAX_VERBOSE - // cout << "extend " << n << "bytes on page=" << page << " pageOffset=" << - // pageOffset << std::endl; - // //??? -#endif - memset( page_buffer + pageOffset, 0, n ); - writePhysicalPage( page_buffer, page ); - - nWrite -= n; - pageOffset = 0; - ++page; - - if ( nWrite < logicalPageSize ) - { - n = static_cast( nWrite ); - } - else - { - n = logicalPageSize; - } - } - - //??? what if loop above throws, logicalLength_ may be wrong - logicalLength_ = newLogicalLength; - - /// When done, leave cursor at end of file - seek( newLogicalLength, Logical ); -} - -void CheckedFile::close() -{ - if ( fd_ >= 0 ) - { -#if defined( _MSC_VER ) - int result = ::_close( fd_ ); -#elif defined( __GNUC__ ) - int result = ::close( fd_ ); -#else -#error "no supported compiler defined" -#endif - if ( result < 0 ) - { - throw E57_EXCEPTION2( E57_ERROR_CLOSE_FAILED, "fileName=" + fileName_ + " result=" + toString( result ) ); - } - - fd_ = -1; - } - - if ( bufView_ ) - { - delete bufView_; - bufView_ = nullptr; - - // WARNING: do NOT delete buffer of bufView_ because - // pointer is handled by user !! - } -} - -void CheckedFile::unlink() -{ - close(); - - /// Try to remove the file, don't report a failure - int result = std::remove( fileName_.c_str() ); //??? unicode support here - (void)result; // this maybe unused -#ifdef E57_MAX_VERBOSE - if ( result < 0 ) - { - std::cout << "std::remove() failed, result=" << result << std::endl; - } -#endif -} - -inline uint32_t swap_uint32( uint32_t val ) -{ - val = ( ( val << 8 ) & 0xFF00FF00 ) | ( ( val >> 8 ) & 0xFF00FF ); - - return ( val << 16 ) | ( val >> 16 ); -} - -/// Calc CRC32C of given data -uint32_t CheckedFile::checksum( char *buf, size_t size ) const -{ - static const CRC::Parameters sCRCParams{ 0x1EDC6F41, 0xFFFFFFFF, 0xFFFFFFFF, true, true }; - - static const CRC::Table sCRCTable = sCRCParams.MakeTable(); - - auto crc = CRC::Calculate( buf, size, sCRCTable ); - - // (Andy) I don't understand why we need to swap bytes here - crc = swap_uint32( crc ); - - return crc; -} - -void CheckedFile::verifyChecksum( char *page_buffer, size_t page ) -{ - const uint32_t check_sum = checksum( page_buffer, logicalPageSize ); - const uint32_t check_sum_in_page = *reinterpret_cast( &page_buffer[logicalPageSize] ); - - if ( check_sum_in_page != check_sum ) - { - const uint64_t physicalLength = length( Physical ); - - throw E57_EXCEPTION2( E57_ERROR_BAD_CHECKSUM, - "fileName=" + fileName_ + " computedChecksum=" + toString( check_sum ) + - " storedChecksum=" + toString( check_sum_in_page ) + " page=" + toString( page ) + - " length=" + toString( physicalLength ) ); - } -} - -void CheckedFile::getCurrentPageAndOffset( uint64_t &page, size_t &pageOffset, OffsetMode omode ) -{ - const uint64_t pos = position( omode ); - - if ( omode == Physical ) - { - page = pos >> physicalPageSizeLog2; - pageOffset = static_cast( pos & physicalPageSizeMask ); - } - else - { - page = pos / logicalPageSize; - pageOffset = static_cast( pos - page * logicalPageSize ); - } -} - -void CheckedFile::readPhysicalPage( char *page_buffer, uint64_t page ) -{ -#ifdef E57_MAX_VERBOSE - // cout << "readPhysicalPage, page:" << page << std::endl; -#endif - -#ifdef E57_CHECK_FILE_DEBUG - const uint64_t physicalLength = length( Physical ); - - assert( page * physicalPageSize < physicalLength ); -#endif - - /// Seek to start of physical page - seek( page * physicalPageSize, Physical ); - - if ( ( fd_ < 0 ) && bufView_ ) - { - bufView_->read( page_buffer, physicalPageSize ); - return; - } - -#if defined( _MSC_VER ) - int result = ::_read( fd_, page_buffer, physicalPageSize ); -#elif defined( __GNUC__ ) - ssize_t result = ::read( fd_, page_buffer, physicalPageSize ); -#else -#error "no supported compiler defined" -#endif - - if ( result < 0 || static_cast( result ) != physicalPageSize ) - { - throw E57_EXCEPTION2( E57_ERROR_READ_FAILED, "fileName=" + fileName_ + " result=" + toString( result ) ); - } -} - -void CheckedFile::writePhysicalPage( char *page_buffer, uint64_t page ) -{ -#ifdef E57_MAX_VERBOSE - // cout << "writePhysicalPage, page:" << page << std::endl; -#endif - - /// Append checksum - uint32_t check_sum = checksum( page_buffer, logicalPageSize ); - *reinterpret_cast( &page_buffer[logicalPageSize] ) = check_sum; //??? little endian dependency - - /// Seek to start of physical page - seek( page * physicalPageSize, Physical ); - -#if defined( _MSC_VER ) - int result = ::_write( fd_, page_buffer, physicalPageSize ); -#elif defined( __GNUC__ ) - ssize_t result = ::write( fd_, page_buffer, physicalPageSize ); -#else -#error "no supported compiler defined" -#endif - - if ( result < 0 ) - { - throw E57_EXCEPTION2( E57_ERROR_WRITE_FAILED, "fileName=" + fileName_ + " result=" + toString( result ) ); - } -} +/* + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +// convenience helper for all the BSDs +#if defined( __FreeBSD__ ) || defined( __NetBSD__ ) || defined( __OpenBSD__ ) +#define __BSD +#endif + +#if defined( _WIN32 ) +#if defined( _MSC_VER ) +#include +#include +#elif defined( __GNUC__ ) +#define _LARGEFILE64_SOURCE +#define __LARGE64_FILES +#include +#include +#include +#else +#error "no supported compiler defined" +#endif +#elif defined( __linux__ ) +#define _LARGEFILE64_SOURCE +#define __LARGE64_FILES +#include +#include +#include +#elif defined( __APPLE__ ) +#include +#include +#elif defined( __BSD ) +#include +#include +#include +#else +#error "no supported OS platform defined" +#endif + +#include +#include +#include +#include + +// This is fixed in a newer version of CRCpp. +// https://github.com/d-bahr/CRCpp/issues/17 +// TODO: Remove when new CRCpp is released. +#if defined( _MSC_VER ) +// Disable warning about "conditional expression is constant". +#pragma warning( push ) +#pragma warning( disable : 4127 ) +#endif +#include "CRC.h" +#if defined( _MSC_VER ) +#pragma warning( pop ) +#endif + +#include "CheckedFile.h" +#include "StringFunctions.h" + +// #define E57_CHECK_FILE_DEBUG +#ifdef E57_CHECK_FILE_DEBUG +#include +#endif + +using namespace e57; + +// These extra definitions are required in C++11. +// In C++17, "static constexpr" is implicitly inline, so these are not required. +constexpr size_t CheckedFile::physicalPageSizeLog2; +constexpr size_t CheckedFile::physicalPageSize; +constexpr uint64_t CheckedFile::physicalPageSizeMask; +constexpr size_t CheckedFile::logicalPageSize; + +namespace +{ + inline uint32_t swap_uint32( uint32_t val ) + { + val = ( ( val << 8 ) & 0xFF00FF00 ) | ( ( val >> 8 ) & 0xFF00FF ); + + return ( val << 16 ) | ( val >> 16 ); + } + + /// Calc CRC32C of given data + uint32_t checksum( char *buf, size_t size ) + { + static const CRC::Parameters sCRCParams{ 0x1EDC6F41, 0xFFFFFFFF, 0xFFFFFFFF, + true, true }; + + static const CRC::Table sCRCTable = sCRCParams.MakeTable(); + + auto crc = CRC::Calculate( buf, size, sCRCTable ); + + // (Andy) I don't understand why we need to swap bytes here + crc = swap_uint32( crc ); + + return crc; + } +} + +/// Tool class to read buffer efficiently without multiplying copy operations. +/// +/// @warning Pointer input is handled by user! +class e57::BufferView +{ +public: + /// @param [in] input filled buffer owned by caller + /// @param [in] size size of input + BufferView( const char *input, uint64_t size ) : streamSize_( size ), stream_( input ) + { + } + + uint64_t pos() const + { + return cursorStream_; + } + + bool seek( uint64_t offset, int whence ) + { + if ( whence == SEEK_CUR ) + { + cursorStream_ += offset; + } + else if ( whence == SEEK_SET ) + { + cursorStream_ = offset; + } + else if ( whence == SEEK_END ) + { + cursorStream_ = streamSize_ - offset; + } + + if ( cursorStream_ > streamSize_ ) + { + cursorStream_ = streamSize_; + return false; + } + + return true; + } + + void read( char *buffer, uint64_t count ) + { + const uint64_t start = cursorStream_; + for ( uint64_t i = 0; i < count; ++i ) + { + buffer[i] = stream_[start + i]; + ++cursorStream_; + } + } + +private: + const uint64_t streamSize_; + uint64_t cursorStream_ = 0; + const char *stream_; +}; + +CheckedFile::CheckedFile( const ustring &fileName, Mode mode, ReadChecksumPolicy policy ) : + fileName_( fileName ), checkSumPolicy_( policy ) +{ + switch ( mode ) + { + case Read: + { +#if defined( _MSC_VER ) + constexpr int readFlags = O_RDONLY | O_BINARY; +#else + constexpr int readFlags = O_RDONLY; +#endif + + fd_ = open64( fileName_, readFlags, 0 ); + + readOnly_ = true; + + physicalLength_ = lseek64( 0LL, SEEK_END ); + lseek64( 0, SEEK_SET ); + + logicalLength_ = physicalToLogical( physicalLength_ ); + } + break; + + case Write: + { + // File truncated to zero length if already exists + +#if defined( _MSC_VER ) + constexpr int writeFlags = O_RDWR | O_CREAT | O_TRUNC | O_BINARY; + constexpr int writeMode = S_IREAD | S_IWRITE; +#else + constexpr int writeFlags = O_RDWR | O_CREAT | O_TRUNC; + constexpr int writeMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; +#endif + + fd_ = open64( fileName_, writeFlags, writeMode ); + } + break; + } +} + +CheckedFile::CheckedFile( const char *input, uint64_t size, ReadChecksumPolicy policy ) : + fileName_( "" ), checkSumPolicy_( policy ) +{ + bufView_ = new BufferView( input, size ); + + readOnly_ = true; + + physicalLength_ = lseek64( 0LL, SEEK_END ); + lseek64( 0, SEEK_SET ); + + logicalLength_ = physicalToLogical( physicalLength_ ); +} + +int CheckedFile::open64( const ustring &fileName, int flags, int mode ) +{ +#if defined( _MSC_VER ) + // Ref: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/sopen-s-wsopen-s + + // Handle UTF-8 file names - Windows requires conversion to UTF-16 + std::wstring_convert> converter; + std::wstring widePath = converter.from_bytes( fileName ); + + int handle; + errno_t err = _wsopen_s( &handle, widePath.c_str(), flags, _SH_DENYNO, mode ); + if ( err != 0 ) + { +// MSVC doesn't implement strerrorlen_s for some unknown reason, so just disable the warning +#pragma warning( push ) +#pragma warning( disable : 4996 ) + + throw E57_EXCEPTION2( ErrorOpenFailed, "errno=" + toString( errno ) + " error='" + + strerror( errno ) + "' fileName=" + fileName + + " flags=" + toString( flags ) + + " mode=" + toString( mode ) ); + +#pragma warning( pop ) + } + return handle; +#elif defined( __GNUC__ ) + int fd = ::open( fileName_.c_str(), flags, mode ); + if ( fd < 0 ) + { + throw E57_EXCEPTION2( ErrorOpenFailed, "errno=" + toString( errno ) + " error='" + + strerror( errno ) + "' fileName=" + fileName + + " flags=" + toString( flags ) + + " mode=" + toString( mode ) ); + } + return fd; +#else +#error "no supported compiler defined" +#endif +} + +CheckedFile::~CheckedFile() +{ + try + { + close(); //??? what if already closed? + } + catch ( ... ) + { + //??? report? + } +} + +void CheckedFile::read( char *buf, size_t nRead, size_t /*bufSize*/ ) +{ + //??? what if read past logical end?, or physical end? + //??? need to keep track of logical length? + //??? check bufSize OK + + const uint64_t end = position( Logical ) + nRead; + const uint64_t logicalLength = length( Logical ); + + if ( end > logicalLength ) + { + throw E57_EXCEPTION2( ErrorInternal, "fileName=" + fileName_ + " end=" + toString( end ) + + " length=" + toString( logicalLength ) ); + } + + uint64_t page = 0; + size_t pageOffset = 0; + + getCurrentPageAndOffset( page, pageOffset ); + + size_t n = std::min( nRead, logicalPageSize - pageOffset ); + + // Allocate temp page buffer + std::vector page_buffer_v( physicalPageSize ); + char *page_buffer = page_buffer_v.data(); + + while ( nRead > 0 ) + { + readPhysicalPage( page_buffer, page ); + + switch ( checkSumPolicy_ ) + { + case ChecksumPolicy::ChecksumNone: + break; + + case ChecksumPolicy::ChecksumAll: + verifyChecksum( page_buffer, page ); + break; + + default: + { + const auto checksumMod = + static_cast( std::nearbyint( 100.0 / checkSumPolicy_ ) ); + + if ( !( page % checksumMod ) || ( nRead < physicalPageSize ) ) + { + verifyChecksum( page_buffer, page ); + } + } + break; + } + + memcpy( buf, page_buffer + pageOffset, n ); + + buf += n; + nRead -= n; + pageOffset = 0; + ++page; + + n = std::min( nRead, logicalPageSize ); + } + + // When done, leave cursor just past end of last byte read + seek( end, Logical ); +} + +void CheckedFile::write( const char *buf, size_t nWrite ) +{ +#ifdef E57_VERBOSE + // cout << "write nWrite=" << nWrite << " position()="<< position() << std::endl; + // //??? +#endif + if ( readOnly_ ) + { + throw E57_EXCEPTION2( ErrorFileReadOnly, "fileName=" + fileName_ ); + } + + uint64_t end = position( Logical ) + nWrite; + + uint64_t page = 0; + size_t pageOffset = 0; + + getCurrentPageAndOffset( page, pageOffset ); + + size_t n = std::min( nWrite, logicalPageSize - pageOffset ); + + // Allocate temp page buffer + std::vector page_buffer_v( physicalPageSize ); + char *page_buffer = page_buffer_v.data(); + + while ( nWrite > 0 ) + { + const uint64_t physicalLength = length( Physical ); + + if ( page * physicalPageSize < physicalLength ) + { + readPhysicalPage( page_buffer, page ); + } + +#ifdef E57_VERBOSE + // cout << " page_buffer[0] read: '" << page_buffer[0] << "'" << std::endl; + // cout << "copy " << n << "bytes to page=" << page << " pageOffset=" << + // pageOffset << " buf='"; //??? for (size_t i=0; i < n; i++) cout << + // buf[i]; cout << "'" << std::endl; +#endif + memcpy( page_buffer + pageOffset, buf, n ); + writePhysicalPage( page_buffer, page ); +#ifdef E57_VERBOSE + // cout << " page_buffer[0] after write: '" << page_buffer[0] << "'" << + // std::endl; //??? +#endif + buf += n; + nWrite -= n; + pageOffset = 0; + page++; + n = std::min( nWrite, logicalPageSize ); + } + + if ( end > logicalLength_ ) + { + logicalLength_ = end; + } + + // When done, leave cursor just past end of buf + seek( end, Logical ); +} + +CheckedFile &CheckedFile::operator<<( const ustring &s ) +{ + write( s.c_str(), s.length() ); //??? should be times size of uchar? + return ( *this ); +} + +CheckedFile &CheckedFile::operator<<( int64_t i ) +{ + std::stringstream ss; + ss << i; + return ( *this << ss.str() ); +} + +CheckedFile &CheckedFile::operator<<( uint64_t i ) +{ + std::stringstream ss; + ss << i; + return ( *this << ss.str() ); +} + +CheckedFile &CheckedFile::operator<<( float f ) +{ + //??? is 7 digits right number? + return writeFloatingPoint( f, 7 ); +} + +CheckedFile &CheckedFile::operator<<( double d ) +{ + //??? is 17 digits right number? + return writeFloatingPoint( d, 17 ); +} + +template CheckedFile &CheckedFile::writeFloatingPoint( FTYPE value, int precision ) +{ + static_assert( std::is_floating_point::value, "Floating point type required." ); + +#ifdef E57_VERBOSE + std::cout << "CheckedFile::writeFloatingPoint, value=" << value << " precision=" << precision + << std::endl; +#endif + + return *this << floatingPointToStr( value, precision ); +} + +void CheckedFile::seek( uint64_t offset, OffsetMode omode ) +{ + //??? check for seek beyond logicalLength_ + const auto pos = + static_cast( omode == Physical ? offset : logicalToPhysical( offset ) ); + +#ifdef E57_VERBOSE + // cout << "seek offset=" << offset << " omode=" << omode << " pos=" << pos + // << std::endl; //??? +#endif + lseek64( pos, SEEK_SET ); +} + +uint64_t CheckedFile::lseek64( int64_t offset, int whence ) +{ + if ( ( fd_ < 0 ) && ( bufView_ != nullptr ) ) + { + const auto uoffset = static_cast( offset ); + + if ( bufView_->seek( uoffset, whence ) ) + { + return bufView_->pos(); + } + + throw E57_EXCEPTION2( ErrorSeekFailed, "fileName=" + fileName_ + + " offset=" + toString( offset ) + + " whence=" + toString( whence ) ); + } + +#if defined( _WIN32 ) + __int64 result = _lseeki64( fd_, offset, whence ); +#elif defined( __linux__ ) + int64_t result = ::lseek64( fd_, offset, whence ); +#elif defined( __APPLE__ ) || defined( __BSD ) + int64_t result = ::lseek( fd_, offset, whence ); +#else +#error "no supported OS platform defined" +#endif + + if ( result < 0 ) + { + throw E57_EXCEPTION2( ErrorSeekFailed, + "fileName=" + fileName_ + " offset=" + toString( offset ) + + " whence=" + toString( whence ) + " result=" + toString( result ) ); + } + + return static_cast( result ); +} + +uint64_t CheckedFile::position( OffsetMode omode ) +{ + // Get current file cursor position + const uint64_t pos = lseek64( 0LL, SEEK_CUR ); + + if ( omode == Physical ) + { + return pos; + } + + return physicalToLogical( pos ); +} + +uint64_t CheckedFile::length( OffsetMode omode ) +{ + if ( omode == Physical ) + { + if ( readOnly_ ) + { + return physicalLength_; + } + + // Current file position + uint64_t original_pos = lseek64( 0LL, SEEK_CUR ); + + // End file position + uint64_t end_pos = lseek64( 0LL, SEEK_END ); + + // Restore original position + lseek64( original_pos, SEEK_SET ); + + return end_pos; + } + + return logicalLength_; +} + +void CheckedFile::extend( uint64_t newLength, OffsetMode omode ) +{ +#ifdef E57_VERBOSE + // cout << "extend newLength=" << newLength << " omode="<< omode << std::endl; + // //??? +#endif + if ( readOnly_ ) + { + throw E57_EXCEPTION2( ErrorFileReadOnly, "fileName=" + fileName_ ); + } + + uint64_t newLogicalLength = 0; + + if ( omode == Physical ) + { + newLogicalLength = physicalToLogical( newLength ); + } + else + { + newLogicalLength = newLength; + } + + uint64_t currentLogicalLength = length( Logical ); + + // Make sure we are trying to make file longer + if ( newLogicalLength < currentLogicalLength ) + { + throw E57_EXCEPTION2( ErrorInternal, + "fileName=" + fileName_ + " newLength=" + toString( newLogicalLength ) + + " currentLength=" + toString( currentLogicalLength ) ); + } + + // Calc how may zero bytes we have to add to end + uint64_t nWrite = newLogicalLength - currentLogicalLength; + + // Seek to current end of file + seek( currentLogicalLength, Logical ); + + uint64_t page = 0; + size_t pageOffset = 0; + + getCurrentPageAndOffset( page, pageOffset ); + + // Calc first write size (may be partial page) + // Watch out for different int sizes here. + size_t n = 0; + + if ( nWrite < logicalPageSize - pageOffset ) + { + n = static_cast( nWrite ); + } + else + { + n = logicalPageSize - pageOffset; + } + + // Allocate temp page buffer + std::vector page_buffer_v( physicalPageSize ); + char *page_buffer = page_buffer_v.data(); + + while ( nWrite > 0 ) + { + const uint64_t physicalLength = length( Physical ); + + if ( page * physicalPageSize < physicalLength ) + { + readPhysicalPage( page_buffer, page ); + } + +#ifdef E57_VERBOSE + // cout << "extend " << n << "bytes on page=" << page << " pageOffset=" << + // pageOffset << std::endl; + // //??? +#endif + memset( page_buffer + pageOffset, 0, n ); + writePhysicalPage( page_buffer, page ); + + nWrite -= n; + pageOffset = 0; + ++page; + + if ( nWrite < logicalPageSize ) + { + n = static_cast( nWrite ); + } + else + { + n = logicalPageSize; + } + } + + //??? what if loop above throws, logicalLength_ may be wrong + logicalLength_ = newLogicalLength; + + // When done, leave cursor at end of file + seek( newLogicalLength, Logical ); +} + +void CheckedFile::close() +{ + if ( fd_ >= 0 ) + { +#if defined( _MSC_VER ) + int result = ::_close( fd_ ); +#elif defined( __GNUC__ ) + int result = ::close( fd_ ); +#else +#error "no supported compiler defined" +#endif + if ( result < 0 ) + { + throw E57_EXCEPTION2( ErrorCloseFailed, + "fileName=" + fileName_ + " result=" + toString( result ) ); + } + + fd_ = -1; + } + + if ( bufView_ != nullptr ) + { + delete bufView_; + bufView_ = nullptr; + + // WARNING: do NOT delete buffer of bufView_ because + // pointer is handled by user !! + } +} + +void CheckedFile::unlink() +{ + close(); + + // Try to remove the file, don't report a failure + int result = std::remove( fileName_.c_str() ); //??? unicode support here +#ifdef E57_VERBOSE + if ( result < 0 ) + { + std::cout << "std::remove() failed, result=" << result << std::endl; + } +#else + UNUSED( result ); +#endif +} + +void CheckedFile::verifyChecksum( char *page_buffer, uint64_t page ) +{ + const uint32_t check_sum = checksum( page_buffer, logicalPageSize ); + const uint32_t check_sum_in_page = + *reinterpret_cast( &page_buffer[logicalPageSize] ); + + if ( check_sum_in_page != check_sum ) + { + const uint64_t physicalLength = length( Physical ); + + throw E57_EXCEPTION2( ErrorBadChecksum, + "fileName=" + fileName_ + " computedChecksum=" + toString( check_sum ) + + " storedChecksum=" + toString( check_sum_in_page ) + " page=" + + toString( page ) + " length=" + toString( physicalLength ) ); + } +} + +void CheckedFile::getCurrentPageAndOffset( uint64_t &page, size_t &pageOffset, OffsetMode omode ) +{ + const uint64_t pos = position( omode ); + + if ( omode == Physical ) + { + page = pos >> physicalPageSizeLog2; + pageOffset = static_cast( pos & physicalPageSizeMask ); + } + else + { + page = pos / logicalPageSize; + pageOffset = static_cast( pos - page * logicalPageSize ); + } +} + +void CheckedFile::readPhysicalPage( char *page_buffer, uint64_t page ) +{ +#ifdef E57_VERBOSE + // cout << "readPhysicalPage, page:" << page << std::endl; +#endif + +#ifdef E57_CHECK_FILE_DEBUG + const uint64_t physicalLength = length( Physical ); + + assert( page * physicalPageSize < physicalLength ); +#endif + + // Seek to start of physical page + seek( page * physicalPageSize, Physical ); + + if ( ( fd_ < 0 ) && ( bufView_ != nullptr ) ) + { + bufView_->read( page_buffer, physicalPageSize ); + return; + } + +#if defined( _MSC_VER ) + int result = ::_read( fd_, page_buffer, physicalPageSize ); +#elif defined( __GNUC__ ) + ssize_t result = ::read( fd_, page_buffer, physicalPageSize ); +#else +#error "no supported compiler defined" +#endif + + if ( result < 0 || static_cast( result ) != physicalPageSize ) + { + throw E57_EXCEPTION2( ErrorReadFailed, + "fileName=" + fileName_ + " result=" + toString( result ) ); + } +} + +void CheckedFile::writePhysicalPage( char *page_buffer, uint64_t page ) +{ +#ifdef E57_VERBOSE + // cout << "writePhysicalPage, page:" << page << std::endl; +#endif + + // Append checksum + uint32_t check_sum = checksum( page_buffer, logicalPageSize ); + *reinterpret_cast( &page_buffer[logicalPageSize] ) = + check_sum; //??? little endian dependency + + // Seek to start of physical page + seek( page * physicalPageSize, Physical ); + +#if defined( _MSC_VER ) + int result = ::_write( fd_, page_buffer, physicalPageSize ); +#elif defined( __GNUC__ ) + ssize_t result = ::write( fd_, page_buffer, physicalPageSize ); +#else +#error "no supported compiler defined" +#endif + + if ( result < 0 ) + { + throw E57_EXCEPTION2( ErrorWriteFailed, + "fileName=" + fileName_ + " result=" + toString( result ) ); + } +} diff --git a/src/3rdParty/libE57Format/src/CheckedFile.h b/src/3rdParty/libE57Format/src/CheckedFile.h index 3163c2887515c..8ff4372752c74 100644 --- a/src/3rdParty/libE57Format/src/CheckedFile.h +++ b/src/3rdParty/libE57Format/src/CheckedFile.h @@ -1,128 +1,129 @@ -/* - * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) - * Modified work Copyright 2018 - 2020 Andy Maloney - * - * Permission is hereby granted, free of charge, to any person or organization - * obtaining a copy of the software and accompanying documentation covered by - * this license (the "Software") to use, reproduce, display, distribute, - * execute, and transmit the Software, and to prepare derivative works of the - * Software, and to permit third-parties to whom the Software is furnished to - * do so, all subject to the following: - * - * The copyright notices in the Software and this entire statement, including - * the above license grant, this restriction and the following disclaimer, - * must be included in all copies of the Software, in whole or in part, and - * all derivative works of the Software, unless such copies or derivative - * works are solely in the form of machine-executable object code generated by - * a source language processor. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT - * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE - * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - */ - -#pragma once - -#include - -#include "Common.h" - -namespace e57 -{ - /// Tool class to read buffer efficiently without - /// multiplying copy operations. - /// - /// WARNING: pointer input is handled by user! - class BufferView; - - class CheckedFile - { - public: - static constexpr size_t physicalPageSizeLog2 = 10; // physical page size is 2 raised to this power - static constexpr size_t physicalPageSize = 1 << physicalPageSizeLog2; - static constexpr uint64_t physicalPageSizeMask = physicalPageSize - 1; - static constexpr size_t logicalPageSize = physicalPageSize - 4; - - public: - enum Mode - { - ReadOnly, - WriteCreate, - WriteExisting - }; - - enum OffsetMode - { - Logical, - Physical - }; - - CheckedFile( const e57::ustring &fileName, Mode mode, ReadChecksumPolicy policy ); - CheckedFile( const char *input, uint64_t size, ReadChecksumPolicy policy ); - ~CheckedFile(); - - void read( char *buf, size_t nRead, size_t bufSize = 0 ); - void write( const char *buf, size_t nWrite ); - CheckedFile &operator<<( const e57::ustring &s ); - CheckedFile &operator<<( int64_t i ); - CheckedFile &operator<<( uint64_t i ); - CheckedFile &operator<<( float f ); - CheckedFile &operator<<( double d ); - void seek( uint64_t offset, OffsetMode omode = Logical ); - uint64_t position( OffsetMode omode = Logical ); - uint64_t length( OffsetMode omode = Logical ); - void extend( uint64_t newLength, OffsetMode omode = Logical ); - e57::ustring fileName() const - { - return fileName_; - } - void close(); - void unlink(); - - static inline uint64_t logicalToPhysical( uint64_t logicalOffset ); - static inline uint64_t physicalToLogical( uint64_t physicalOffset ); - - private: - uint32_t checksum( char *buf, size_t size ) const; - void verifyChecksum( char *page_buffer, size_t page ); - - template CheckedFile &writeFloatingPoint( FTYPE value, int precision ); - - void getCurrentPageAndOffset( uint64_t &page, size_t &pageOffset, OffsetMode omode = Logical ); - void readPhysicalPage( char *page_buffer, uint64_t page ); - void writePhysicalPage( char *page_buffer, uint64_t page ); - int open64( const e57::ustring &fileName, int flags, int mode ); - uint64_t lseek64( int64_t offset, int whence ); - - e57::ustring fileName_; - uint64_t logicalLength_ = 0; - uint64_t physicalLength_ = 0; - - ReadChecksumPolicy checkSumPolicy_ = CHECKSUM_POLICY_ALL; - - int fd_ = -1; - BufferView *bufView_ = nullptr; - bool readOnly_ = false; - }; - - inline uint64_t CheckedFile::logicalToPhysical( uint64_t logicalOffset ) - { - const uint64_t page = logicalOffset / logicalPageSize; - const uint64_t remainder = logicalOffset - page * logicalPageSize; - - return page * physicalPageSize + remainder; - } - - inline uint64_t CheckedFile::physicalToLogical( uint64_t physicalOffset ) - { - const uint64_t page = physicalOffset >> physicalPageSizeLog2; - const size_t remainder = static_cast( physicalOffset & physicalPageSizeMask ); - - return page * logicalPageSize + std::min( remainder, logicalPageSize ); - } - -} +/* + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#pragma once + +#include + +#include "Common.h" + +namespace e57 +{ + // Tool class to read buffer efficiently without + // multiplying copy operations. + // + // WARNING: pointer input is handled by user! + class BufferView; + + class CheckedFile + { + public: + // physical page size is 2 raised to this power + static constexpr size_t physicalPageSizeLog2 = 10; + static constexpr size_t physicalPageSize = 1 << physicalPageSizeLog2; + static constexpr uint64_t physicalPageSizeMask = physicalPageSize - 1; + static constexpr size_t logicalPageSize = physicalPageSize - 4; + + public: + enum Mode + { + Read, + Write, + }; + + enum OffsetMode + { + Logical, + Physical + }; + + CheckedFile( const e57::ustring &fileName, Mode mode, ReadChecksumPolicy policy ); + CheckedFile( const char *input, uint64_t size, ReadChecksumPolicy policy ); + ~CheckedFile(); + + void read( char *buf, size_t nRead, size_t bufSize = 0 ); + void write( const char *buf, size_t nWrite ); + CheckedFile &operator<<( const e57::ustring &s ); + CheckedFile &operator<<( int64_t i ); + CheckedFile &operator<<( uint64_t i ); + CheckedFile &operator<<( float f ); + CheckedFile &operator<<( double d ); + void seek( uint64_t offset, OffsetMode omode = Logical ); + uint64_t position( OffsetMode omode = Logical ); + uint64_t length( OffsetMode omode = Logical ); + void extend( uint64_t newLength, OffsetMode omode = Logical ); + + e57::ustring fileName() const + { + return fileName_; + } + + void close(); + void unlink(); + + static inline uint64_t logicalToPhysical( uint64_t logicalOffset ); + static inline uint64_t physicalToLogical( uint64_t physicalOffset ); + + private: + void verifyChecksum( char *page_buffer, uint64_t page ); + + template CheckedFile &writeFloatingPoint( FTYPE value, int precision ); + + void getCurrentPageAndOffset( uint64_t &page, size_t &pageOffset, + OffsetMode omode = Logical ); + void readPhysicalPage( char *page_buffer, uint64_t page ); + void writePhysicalPage( char *page_buffer, uint64_t page ); + int open64( const e57::ustring &fileName, int flags, int mode ); + uint64_t lseek64( int64_t offset, int whence ); + + e57::ustring fileName_; + uint64_t logicalLength_ = 0; + uint64_t physicalLength_ = 0; + + ReadChecksumPolicy checkSumPolicy_ = ChecksumPolicy::ChecksumAll; + + int fd_ = -1; + BufferView *bufView_ = nullptr; + bool readOnly_ = false; + }; + + inline uint64_t CheckedFile::logicalToPhysical( uint64_t logicalOffset ) + { + const uint64_t page = logicalOffset / logicalPageSize; + const uint64_t remainder = logicalOffset - page * logicalPageSize; + + return page * physicalPageSize + remainder; + } + + inline uint64_t CheckedFile::physicalToLogical( uint64_t physicalOffset ) + { + const uint64_t page = physicalOffset >> physicalPageSizeLog2; + const auto remainder = static_cast( physicalOffset & physicalPageSizeMask ); + + return page * logicalPageSize + std::min( remainder, logicalPageSize ); + } +} diff --git a/src/3rdParty/libE57Format/src/Common.h b/src/3rdParty/libE57Format/src/Common.h index 355d59662dea0..2f38ab7fbd2d2 100644 --- a/src/3rdParty/libE57Format/src/Common.h +++ b/src/3rdParty/libE57Format/src/Common.h @@ -1,183 +1,82 @@ -/* - * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) - * Modified work Copyright 2018 - 2020 Andy Maloney - * - * Permission is hereby granted, free of charge, to any person or organization - * obtaining a copy of the software and accompanying documentation covered by - * this license (the "Software") to use, reproduce, display, distribute, - * execute, and transmit the Software, and to prepare derivative works of the - * Software, and to permit third-parties to whom the Software is furnished to - * do so, all subject to the following: - * - * The copyright notices in the Software and this entire statement, including - * the above license grant, this restriction and the following disclaimer, - * must be included in all copies of the Software, in whole or in part, and - * all derivative works of the Software, unless such copies or derivative - * works are solely in the form of machine-executable object code generated by - * a source language processor. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT - * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE - * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -// Define the following symbol adds some functions to the API for implementation -// purposes. These functions are not available to a normal API user. -#define E57_INTERNAL_IMPLEMENTATION_ENABLE 1 -#include "E57Format.h" - -#ifdef _MSC_VER -// Disable MSVC warning: warning C4224: nonstandard extension used : formal -// parameter 'locale' was previously defined as a type -#pragma warning( disable : 4224 ) -#endif - -namespace e57 -{ -//!!! inline these rather than macros? -#define E57_EXCEPTION1( ecode ) \ - ( E57Exception( ( ecode ), ustring(), __FILE__, __LINE__, static_cast( __FUNCTION__ ) ) ) -#define E57_EXCEPTION2( ecode, context ) \ - ( E57Exception( ( ecode ), ( context ), __FILE__, __LINE__, static_cast( __FUNCTION__ ) ) ) - - /// Create whitespace of given length, for indenting printouts in dump() - /// functions - inline std::string space( size_t n ) - { - return ( std::string( n, ' ' ) ); - } - - /// Convert number to decimal, hexadecimal, and binary strings (Note hex - /// strings don't have leading zeros). - template std::string toString( T x ) - { - std::ostringstream ss; - ss << x; - return ( ss.str() ); - } - - inline std::string hexString( uint64_t x ) - { - std::ostringstream ss; - ss << "0x" << std::hex << std::setw( 16 ) << std::setfill( '0' ) << x; - return ( ss.str() ); - } - inline std::string hexString( uint32_t x ) - { - std::ostringstream ss; - ss << "0x" << std::hex << std::setw( 8 ) << std::setfill( '0' ) << x; - return ( ss.str() ); - } - inline std::string hexString( uint16_t x ) - { - std::ostringstream ss; - ss << "0x" << std::hex << std::setw( 4 ) << std::setfill( '0' ) << x; - return ( ss.str() ); - } - inline std::string hexString( uint8_t x ) - { - std::ostringstream ss; - ss << "0x" << std::hex << std::setw( 2 ) << std::setfill( '0' ) << static_cast( x ); - return ( ss.str() ); - } - inline std::string binaryString( uint64_t x ) - { - std::ostringstream ss; - for ( int i = 63; i >= 0; i-- ) - { - ss << ( ( x & ( 1LL << i ) ) ? 1 : 0 ); - if ( i > 0 && i % 8 == 0 ) - ss << " "; - } - return ( ss.str() ); - } - inline std::string binaryString( uint32_t x ) - { - std::ostringstream ss; - for ( int i = 31; i >= 0; i-- ) - { - ss << ( ( x & ( 1LL << i ) ) ? 1 : 0 ); - if ( i > 0 && i % 8 == 0 ) - ss << " "; - } - return ( ss.str() ); - } - inline std::string binaryString( uint16_t x ) - { - std::ostringstream ss; - for ( int i = 15; i >= 0; i-- ) - { - ss << ( ( x & ( 1LL << i ) ) ? 1 : 0 ); - if ( i > 0 && i % 8 == 0 ) - ss << " "; - } - return ( ss.str() ); - } - inline std::string binaryString( uint8_t x ) - { - std::ostringstream ss; - for ( int i = 7; i >= 0; i-- ) - { - ss << ( ( x & ( 1LL << i ) ) ? 1 : 0 ); - if ( i > 0 && i % 8 == 0 ) - ss << " "; - } - return ( ss.str() ); - } - inline std::string hexString( int64_t x ) - { - return ( hexString( static_cast( x ) ) ); - } - inline std::string hexString( int32_t x ) - { - return ( hexString( static_cast( x ) ) ); - } - inline std::string hexString( int16_t x ) - { - return ( hexString( static_cast( x ) ) ); - } - inline std::string hexString( int8_t x ) - { - return ( hexString( static_cast( x ) ) ); - } - inline std::string binaryString( int64_t x ) - { - return ( binaryString( static_cast( x ) ) ); - } - inline std::string binaryString( int32_t x ) - { - return ( binaryString( static_cast( x ) ) ); - } - inline std::string binaryString( int16_t x ) - { - return ( binaryString( static_cast( x ) ) ); - } - inline std::string binaryString( int8_t x ) - { - return ( binaryString( static_cast( x ) ) ); - } - - using ImageFileImplSharedPtr = std::shared_ptr; - using ImageFileImplWeakPtr = std::weak_ptr; - using NodeImplSharedPtr = std::shared_ptr; - using NodeImplWeakPtr = std::weak_ptr; - - using StringList = std::vector; - using StringSet = std::set; - - //! generates a new random GUID - std::string generateRandomGUID(); -} +/* + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#pragma once + +#include +#include +#include + +// Define the following symbol adds some functions to the API for implementation +// purposes. These functions are not available to a normal API user. +#define E57_INTERNAL_IMPLEMENTATION_ENABLE 1 +#include "E57Format.h" + +#ifdef _MSC_VER +// Disable MSVC warning: warning C4224: nonstandard extension used : formal +// parameter 'locale' was previously defined as a type +#pragma warning( disable : 4224 ) +#endif + +// Used to mark unused parameters to indicate intent and suppress warnings. +#define UNUSED( expr ) (void)( expr ) + +// For readability of preprocessor using E57_VALIDATION_LEVEL +#define VALIDATION_OFF 0 +#define VALIDATION_BASIC 1 +#define VALIDATION_DEEP 2 + +#define VALIDATE_BASIC ( E57_VALIDATION_LEVEL > VALIDATION_OFF ) +#define VALIDATE_DEEP ( E57_VALIDATION_LEVEL > VALIDATION_BASIC ) + +// Determine if we are building 32 or 64 bit +#if SIZE_MAX == UINT32_MAX +#define E57_32_BIT +#elif SIZE_MAX == UINT64_MAX +#define E57_64_BIT +#endif + +namespace e57 +{ +#define E57_EXCEPTION1( ecode ) \ + ( E57Exception( ( ecode ), ustring(), __FILE__, __LINE__, \ + static_cast( __FUNCTION__ ) ) ) +#define E57_EXCEPTION2( ecode, context ) \ + ( E57Exception( ( ecode ), ( context ), __FILE__, __LINE__, \ + static_cast( __FUNCTION__ ) ) ) + + using ImageFileImplSharedPtr = std::shared_ptr; + using ImageFileImplWeakPtr = std::weak_ptr; + using NodeImplSharedPtr = std::shared_ptr; + using NodeImplWeakPtr = std::weak_ptr; + + using StringList = std::vector; + using StringSet = std::set; + + /// generates a new random GUID + std::string generateRandomGUID(); +} diff --git a/src/3rdParty/libE57Format/src/CompressedVectorNode.cpp b/src/3rdParty/libE57Format/src/CompressedVectorNode.cpp new file mode 100644 index 0000000000000..9de177d5df64b --- /dev/null +++ b/src/3rdParty/libE57Format/src/CompressedVectorNode.cpp @@ -0,0 +1,480 @@ +/* + * CompressedVectorNode.cpp - implementation of public functions of the + * CompressedVectorNode class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file CompressedVectorNode.cpp + +#include "CompressedVectorNodeImpl.h" +#include "StringFunctions.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/*! +@brief Check whether CompressedVectorNode class invariant is true +@copydetails IntegerNode::checkInvariant() +*/ + +void CompressedVectorNode::checkInvariant( bool doRecurse, bool doUpcast ) const +{ + // If destImageFile not open, can't test invariant (almost every call would throw) + if ( !destImageFile().isOpen() ) + { + return; + } + + // If requested, call Node::checkInvariant + if ( doUpcast ) + { + static_cast( *this ).checkInvariant( false, false ); + } + + // Check prototype is good Node + prototype().checkInvariant( doRecurse ); + + // prototype attached state not same as this attached state + if ( prototype().isAttached() != isAttached() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // prototype not root + if ( !prototype().isRoot() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // prototype dest ImageFile not same as this dest ImageFile + if ( prototype().destImageFile() != destImageFile() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Check codecs is good Node + codecs().checkInvariant( doRecurse ); + + // codecs attached state not same as this attached state + if ( codecs().isAttached() != isAttached() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // codecs not root + if ( !codecs().isRoot() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // codecs dest ImageFile not same as this dest ImageFile + if ( codecs().destImageFile() != destImageFile() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } +} + +/*! +@class e57::CompressedVectorNode + +@brief An E57 element containing ordered vector of child nodes, stored in an efficient binary +format. + +@details +The CompressedVectorNode encodes very long sequences of identically typed records. In an E57 file, +the per-point information (coordinates, intensity, color, time stamp etc.) are stored in a +CompressedVectorNode. For time and space efficiency, the CompressedVectorNode data is stored in a +binary section of the E57 file. + +Conceptually, the CompressedVectorNode encodes a structure that looks very much like a homogeneous +VectorNode object. However because of the huge volume of data (E57 files can store more than 10 +billion points) within a CompressedVectorNode, the functions for accessing the data are dramatically +different. CompressedVectorNode data is accessed in large blocks of records (100s to 1000s at a +time). + +Two attributes are required to create a new CompressedVectorNode. + +The first attribute describes the shape of the record that will be stored. This record type +description is called the @c prototype of the CompressedVectorNode. Often the @c prototype will be a +StructNode with a single level of named child elements. However, the prototype can be a tree of any +depth consisting of the following node types: IntegerNode, ScaledIntegerNode, FloatNode, StringNode, +StructureNode, or VectorNode (i.e. CompressedVectorNode and BlobNode are not allowed). Only the node +types and attributes are used in the prototype, the values stored are ignored. For example, if the +prototype contains an IntegerNode, with a value=0, minimum=0, maximum=1023, then this means that +each record will contain an integer that can take any value in the interval [0,1023]. As a second +example, if the prototype contains an ScaledIntegerNode, with a value=0, minimum=0, maximum=1023, +scale=.001, offset=0 then this means that each record will contain an integer that can take any +value in the interval [0,1023] and if a reader requests the scaledValue of the field, the rawValue +should be multiplied by 0.001. + +The second attribute needed to describe a new CompressedVectorNode is the @c codecs description of +how the values of the records are to be represented on the disk. The codec object is a VectorNode of +a particular format that describes the encoding for each field in the record, which codec will be +used to transfer the values to and from the disk. Currently only one codec is defined for E57 files, +the bitPackCodec, which copies the numbers from memory, removes any unused bit positions, and stores +the without additional spaces on the disk. The bitPackCodec has no configuration options or +parameters to tune. In the ASTM standard, if no codec is specified, the bitPackCodec is assumed. So +specifying the @c codecs as an empty VectorNode is equivalent to requesting at all fields in the +record be encoded with the bitPackCodec. + +Other than the @c prototype and @c codecs attributes, the only other state directly accessible is +the number of children (records) in the CompressedVectorNode. The read/write access to the contents +of the CompressedVectorNode is coordinated by two other Foundation API objects: +CompressedVectorReader and CompressedVectorWriter. + +@section CompressedVectorNode_invariant Class Invariant + +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude CompressedVectorNode.cpp +@skip void CompressedVectorNode::checkInvariant +@until ^} + +@see CompressedVectorReader, CompressedVectorWriter, Node +*/ + +/*! +@brief Create an empty CompressedVectorNode, for writing, that will store records specified by the +prototype. + +@param [in] destImageFile The ImageFile where the new node will eventually be stored. +@param [in] prototype A tree that describes the fields in each record of the CompressedVectorNode. +@param [in] codecs A VectorNode describing which codecs should be used for each field described in +the prototype. + +@details +The @a destImageFile indicates which ImageFile the CompressedVectorNode will eventually be attached +to. A node is attached to an ImageFile by adding it underneath the predefined root of the ImageFile +(gotten from ImageFile::root). It is not an error to fail to attach the CompressedVectorNode to the +@a destImageFile. It is an error to attempt to attach the CompressedVectorNode to a different +ImageFile. The CompressedVectorNode may not be written to until it is attached to the destImageFile +tree. + +The @a prototype may be any tree consisting of only the following node types: IntegerNode, +ScaledIntegerNode, FloatNode, StringNode, StructureNode, or VectorNode (i.e. CompressedVectorNode +and BlobNode are not allowed). See CompressedVectorNode for discussion about the @a prototype +argument. + +The @a codecs must be a heterogeneous VectorNode with children as specified in the ASTM E57 data +format standard. Since currently only one codec is supported (bitPackCodec), and it is the default, +passing an empty VectorNode will specify that all record fields will be encoded with bitPackCodec. + +@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be true). +@pre The @a destImageFile must have been opened in write mode (i.e. destImageFile.isWritable() must +be true). +@pre @a prototype must be an unattached root node (i.e. !prototype.isAttached() && +prototype.isRoot()) +@pre @a prototype cannot contain BlobNodes or CompressedVectorNodes. +@pre @a codecs must be an unattached root node (i.e. !codecs.isAttached() && codecs.isRoot()) +@post prototype.isAttached() +@post codecs.isAttached() + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorFileReadOnly +@throw ::ErrorBadPrototype +@throw ::ErrorBadCodecs +@throw ::ErrorAlreadyHasParent +@throw ::ErrorDifferentDestImageFile +@throw ::ErrorInternal All objects in undocumented state + +@see SourceDestBuffer, Node, CompressedVectorNode::reader, CompressedVectorNode::writer +*/ +CompressedVectorNode::CompressedVectorNode( const ImageFile &destImageFile, const Node &prototype, + const VectorNode &codecs ) : + impl_( new CompressedVectorNodeImpl( destImageFile.impl() ) ) +{ + // Because of shared_ptr quirks, can't set prototype,codecs in CompressedVectorNodeImpl(), so set + // it afterwards + impl_->setPrototype( prototype.impl() ); + impl_->setCodecs( codecs.impl() ); +} + +/*! +@brief Is this a root node. +@copydetails Node::isRoot() +*/ +bool CompressedVectorNode::isRoot() const +{ + return impl_->isRoot(); +} + +/*! +@brief Return parent of node, or self if a root node. +@copydetails Node::parent() +*/ +Node CompressedVectorNode::parent() const +{ + return Node( impl_->parent() ); +} + +/// @brief Get absolute pathname of node. +/// @copydetails Node::pathName() +ustring CompressedVectorNode::pathName() const +{ + return impl_->pathName(); +} + +/// @brief Get elementName string, that identifies the node in its parent.. +/// @copydetails Node::elementName() +ustring CompressedVectorNode::elementName() const +{ + return impl_->elementName(); +} + +/// @brief Get the ImageFile that was declared as the destination for the node when it was created. +/// @copydetails Node::destImageFile() +ImageFile CompressedVectorNode::destImageFile() const +{ + return ImageFile( impl_->destImageFile() ); +} + +/// @brief Has node been attached into the tree of an ImageFile. +/// @copydetails Node::isAttached() +bool CompressedVectorNode::isAttached() const +{ + return impl_->isAttached(); +} + +/*! +@brief Get current number of records in a CompressedVectorNode. + +@details +For a CompressedVectorNode with an active CompressedVectorWriter, the returned number will reflect +any writes completed. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return Current number of records in CompressedVectorNode. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorNode::reader, CompressedVectorNode::writer +*/ +int64_t CompressedVectorNode::childCount() const +{ + return impl_->childCount(); +} + +/*! +@brief Get the prototype tree that describes the types in the record. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return A smart Node handle referencing the root of the prototype tree. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorNode::CompressedVectorNode, SourceDestBuffer, CompressedVectorNode::reader, +CompressedVectorNode::writer +*/ +Node CompressedVectorNode::prototype() const +{ + return Node( impl_->getPrototype() ); +} + +/*! +@brief Get the codecs tree that describes the encoder/decoder configuration of the +CompressedVectorNode. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return A smart VectorNode handle referencing the root of the codecs tree. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorNode::CompressedVectorNode, SourceDestBuffer, CompressedVectorNode::reader, +CompressedVectorNode::writer +*/ +VectorNode CompressedVectorNode::codecs() const +{ + return VectorNode( impl_->getCodecs() ); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void CompressedVectorNode::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void CompressedVectorNode::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif + +/*! +@brief Upcast a CompressedVectorNode handle to a generic Node handle. + +@details +An upcast is always safe, and the compiler can automatically insert it for initializations of Node +variables and Node function arguments. + +@return A smart Node handle referencing the underlying object. + +@throw No E57Exceptions. + +@see explanation in Node, Node::type(), CompressedVectorNode(const Node&) +*/ +CompressedVectorNode::operator Node() const +{ + // Implicitly upcast from shared_ptr to SharedNodeImplPtr and + // construct a Node object + return Node( impl_ ); +} + +/*! +@brief Downcast a generic Node handle to a CompressedVectorNode handle. + +@param [in] n The generic handle to downcast. + +@details +The handle @a n must be for an underlying CompressedVectorNode, otherwise an exception is thrown. In +designs that need to avoid the exception, use Node::type() to determine the actual type of the @a n +before downcasting. This function must be explicitly called (c++ compiler cannot insert it +automatically). + +@throw ::ErrorBadNodeDowncast + +@see Node::type(), CompressedVectorNode::operator, Node() +*/ +CompressedVectorNode::CompressedVectorNode( const Node &n ) +{ + if ( n.type() != TypeCompressedVector ) + { + throw E57_EXCEPTION2( ErrorBadNodeDowncast, "nodeType=" + toString( n.type() ) ); + } + + // Set our shared_ptr to the downcast shared_ptr + impl_ = std::static_pointer_cast( n.impl() ); +} + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +CompressedVectorNode::CompressedVectorNode( std::shared_ptr ni ) : + impl_( ni ) +{ +} +/// @endcond + +/*! +@brief Create an iterator object for writing a series of blocks of data to a CompressedVectorNode. + +@param [in] sbufs Vector of memory buffers that will hold data to be written to a +CompressedVectorNode. + +@details +See CompressedVectorWriter::write(std::vector&, unsigned) for discussion about +restrictions on @a sbufs. + +The pathNames in the @a sbufs must match one-to-one with the terminal nodes (i.e. nodes that can +have no children: IntegerNode, ScaledIntegerNode, FloatNode, StringNode) in this +CompressedVectorNode's prototype. It is an error for two SourceDestBuffers in @a dbufs to identify +the same terminal node in the prototype. + +It is an error to call this function if the CompressedVectorNode already has any records (i.e. a +CompressedVectorNode cannot be set twice). + +@pre @a sbufs can't be empty (i.e. sbufs.length() > 0). +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@pre The @a destImageFile must have been opened in write mode (i.e. destImageFile.isWritable()). +@pre The destination ImageFile can't have any readers or writers open +(destImageFile().readerCount()==0 && destImageFile().writerCount()==0) +@pre This CompressedVectorNode must be attached (i.e. isAttached()). +@pre This CompressedVectorNode must have no records (i.e. childCount() == 0). + +@return A smart CompressedVectorWriter handle referencing the underlying iterator object. + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorFileReadOnly +@throw ::ErrorSetTwice +@throw ::ErrorTooManyWriters +@throw ::ErrorTooManyReaders +@throw ::ErrorNodeUnattached +@throw ::ErrorPathUndefined +@throw ::ErrorBufferSizeMismatch +@throw ::ErrorBufferDuplicatePathName +@throw ::ErrorNoBufferForElement +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorWriter, SourceDestBuffer, CompressedVectorNode::CompressedVectorNode, +CompressedVectorNode::prototype +*/ +CompressedVectorWriter CompressedVectorNode::writer( std::vector &sbufs ) +{ + return CompressedVectorWriter( impl_->writer( sbufs ) ); +} + +/*! +@brief Create an iterator object for reading a series of blocks of data from a CompressedVectorNode. + +@param [in] dbufs Vector of memory buffers that will receive data read from a CompressedVectorNode. + +@details +The pathNames in the @a dbufs must identify terminal nodes (i.e. node that can have no children: +IntegerNode, ScaledIntegerNode, FloatNode, StringNode) in this CompressedVectorNode's prototype. It +is an error for two SourceDestBuffers in @a dbufs to identify the same terminal node in the +prototype. It is not an error to create a CompressedVectorReader for an empty CompressedVectorNode. + +@pre @a dbufs can't be empty +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@pre The destination ImageFile can't have any writers open (destImageFile().writerCount()==0) +@pre This CompressedVectorNode must be attached (i.e. isAttached()). + +@return A smart CompressedVectorReader handle referencing the underlying iterator object. + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorTooManyWriters +@throw ::ErrorNodeUnattached +@throw ::ErrorPathUndefined +@throw ::ErrorBufferSizeMismatch +@throw ::ErrorBufferDuplicatePathName +@throw ::ErrorBadCVHeader +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorReader, SourceDestBuffer, CompressedVectorNode::CompressedVectorNode, +CompressedVectorNode::prototype +*/ +CompressedVectorReader CompressedVectorNode::reader( const std::vector &dbufs ) +{ + return CompressedVectorReader( impl_->reader( dbufs ) ); +} diff --git a/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.cpp b/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.cpp index d6bbd53bcb140..3f344baa31732 100644 --- a/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.cpp @@ -30,11 +30,13 @@ #include "CompressedVectorReaderImpl.h" #include "CompressedVectorWriterImpl.h" #include "ImageFileImpl.h" +#include "StringFunctions.h" #include "VectorNodeImpl.h" namespace e57 { - CompressedVectorNodeImpl::CompressedVectorNodeImpl( ImageFileImplWeakPtr destImageFile ) : NodeImpl( destImageFile ) + CompressedVectorNodeImpl::CompressedVectorNodeImpl( ImageFileImplWeakPtr destImageFile ) : + NodeImpl( destImageFile ) { // don't checkImageFileOpen, NodeImpl() will do it } @@ -44,36 +46,37 @@ namespace e57 // don't checkImageFileOpen, ctor did it //??? check ok for proto, no Blob CompressedVector, empty? - //??? throw E57_EXCEPTION2(E57_ERROR_BAD_PROTOTYPE) + //??? throw E57_EXCEPTION2(ErrorBadPrototype) - /// Can't set prototype twice. + // Can't set prototype twice. if ( prototype_ ) { - throw E57_EXCEPTION2( E57_ERROR_SET_TWICE, "this->pathName=" + this->pathName() ); + throw E57_EXCEPTION2( ErrorSetTwice, "this->pathName=" + this->pathName() ); } - /// prototype can't have a parent (must be a root node) + // prototype can't have a parent (must be a root node) if ( !prototype->isRoot() ) { - throw E57_EXCEPTION2( E57_ERROR_ALREADY_HAS_PARENT, - "this->pathName=" + this->pathName() + " prototype->pathName=" + prototype->pathName() ); + throw E57_EXCEPTION2( ErrorAlreadyHasParent, + "this->pathName=" + this->pathName() + + " prototype->pathName=" + prototype->pathName() ); } - /// Verify that prototype is destined for same ImageFile as this is + // Verify that prototype is destined for same ImageFile as this is ImageFileImplSharedPtr thisDest( destImageFile() ); ImageFileImplSharedPtr prototypeDest( prototype->destImageFile() ); if ( thisDest != prototypeDest ) { - throw E57_EXCEPTION2( E57_ERROR_DIFFERENT_DEST_IMAGEFILE, "this->destImageFile" + thisDest->fileName() + - " prototype->destImageFile" + - prototypeDest->fileName() ); + throw E57_EXCEPTION2( ErrorDifferentDestImageFile, + "this->destImageFile" + thisDest->fileName() + + " prototype->destImageFile" + prototypeDest->fileName() ); } - //!!! check for incomplete CompressedVectors when closing file + // !!! check for incomplete CompressedVectors when closing file prototype_ = prototype; - /// Note that prototype is not attached to CompressedVector in a parent/child - /// relationship. This means that prototype is a root node (has no parent). + // Note that prototype is not attached to CompressedVector in a parent/child + // relationship. This means that prototype is a root node (has no parent). } NodeImplSharedPtr CompressedVectorNodeImpl::getPrototype() const @@ -90,33 +93,34 @@ namespace e57 // of strings, codec // substruct - /// Can't set codecs twice. + // Can't set codecs twice. if ( codecs_ ) { - throw E57_EXCEPTION2( E57_ERROR_SET_TWICE, "this->pathName=" + this->pathName() ); + throw E57_EXCEPTION2( ErrorSetTwice, "this->pathName=" + this->pathName() ); } - /// codecs can't have a parent (must be a root node) + // codecs can't have a parent (must be a root node) if ( !codecs->isRoot() ) { - throw E57_EXCEPTION2( E57_ERROR_ALREADY_HAS_PARENT, - "this->pathName=" + this->pathName() + " codecs->pathName=" + codecs->pathName() ); + throw E57_EXCEPTION2( ErrorAlreadyHasParent, + "this->pathName=" + this->pathName() + + " codecs->pathName=" + codecs->pathName() ); } - /// Verify that codecs is destined for same ImageFile as this is + // Verify that codecs is destined for same ImageFile as this is ImageFileImplSharedPtr thisDest( destImageFile() ); ImageFileImplSharedPtr codecsDest( codecs->destImageFile() ); if ( thisDest != codecsDest ) { - throw E57_EXCEPTION2( E57_ERROR_DIFFERENT_DEST_IMAGEFILE, "this->destImageFile" + thisDest->fileName() + - " codecs->destImageFile" + - codecsDest->fileName() ); + throw E57_EXCEPTION2( ErrorDifferentDestImageFile, + "this->destImageFile" + thisDest->fileName() + + " codecs->destImageFile" + codecsDest->fileName() ); } codecs_ = codecs; - /// Note that codecs is not attached to CompressedVector in a parent/child - /// relationship. This means that codecs is a root node (has no parent). + // Note that codecs is not attached to CompressedVector in a parent/child + // relationship. This means that codecs is a root node (has no parent). } std::shared_ptr CompressedVectorNodeImpl::getCodecs() const @@ -131,21 +135,22 @@ namespace e57 //??? is this test a good idea? - /// Same node type? - if ( ni->type() != E57_COMPRESSED_VECTOR ) + // Same node type? + if ( ni->type() != TypeCompressedVector ) { return ( false ); } - std::shared_ptr cvi( std::static_pointer_cast( ni ) ); + std::shared_ptr cvi( + std::static_pointer_cast( ni ) ); - /// recordCount must match + // recordCount must match if ( recordCount_ != cvi->recordCount_ ) { return ( false ); } - /// Prototypes and codecs must match ??? + // Prototypes and codecs must match ??? if ( !prototype_->isTypeEquivalent( cvi->prototype_ ) ) { return ( false ); @@ -160,21 +165,22 @@ namespace e57 bool CompressedVectorNodeImpl::isDefined( const ustring &pathName ) { - throw E57_EXCEPTION2( E57_ERROR_NOT_IMPLEMENTED, "this->pathName=" + this->pathName() + " pathName=" + pathName ); + throw E57_EXCEPTION2( ErrorNotImplemented, + "this->pathName=" + this->pathName() + " pathName=" + pathName ); } void CompressedVectorNodeImpl::setAttachedRecursive() { - /// Mark this node as attached to an ImageFile + // Mark this node as attached to an ImageFile isAttached_ = true; - /// Mark nodes in prototype tree, if defined + // Mark nodes in prototype tree, if defined if ( prototype_ ) { prototype_->setAttachedRecursive(); } - /// Mark nodes in codecs tree if defined + // Mark nodes in codecs tree if defined if ( codecs_ ) { codecs_->setAttachedRecursive(); @@ -187,13 +193,14 @@ namespace e57 return ( recordCount_ ); } - void CompressedVectorNodeImpl::checkLeavesInSet( const StringSet & /*pathNames*/, NodeImplSharedPtr /*origin*/ ) + void CompressedVectorNodeImpl::checkLeavesInSet( const StringSet & /*pathNames*/, + NodeImplSharedPtr /*origin*/ ) { // don't checkImageFileOpen - /// Since only called for prototype nodes, shouldn't be able to get here since - /// CompressedVectors can't be in prototypes - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "this->pathName=" + this->pathName() ); + // Since only called for prototype nodes, shouldn't be able to get here since + // CompressedVectors can't be in prototypes + throw E57_EXCEPTION2( ErrorInternal, "this->pathName=" + this->pathName() ); } void CompressedVectorNodeImpl::writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, @@ -202,7 +209,7 @@ namespace e57 // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName ) + if ( forcedFieldName != nullptr ) { fieldName = forcedFieldName; } @@ -228,7 +235,7 @@ namespace e57 cf << space( indent ) << "\n"; } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void CompressedVectorNodeImpl::dump( int indent, std::ostream &os ) const { os << space( indent ) << "type: CompressedVector" @@ -253,108 +260,115 @@ namespace e57 os << space( indent ) << "codecs: " << std::endl; } os << space( indent ) << "recordCount: " << recordCount_ << std::endl; - os << space( indent ) << "binarySectionLogicalStart: " << binarySectionLogicalStart_ << std::endl; + os << space( indent ) << "binarySectionLogicalStart: " << binarySectionLogicalStart_ + << std::endl; } #endif - std::shared_ptr CompressedVectorNodeImpl::writer( std::vector sbufs ) + std::shared_ptr CompressedVectorNodeImpl::writer( + std::vector sbufs ) { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); ImageFileImplSharedPtr destImageFile( destImageFile_ ); - /// Check don't have any writers/readers open for this ImageFile + // Check don't have any writers/readers open for this ImageFile if ( destImageFile->writerCount() > 0 ) { - throw E57_EXCEPTION2( E57_ERROR_TOO_MANY_WRITERS, + throw E57_EXCEPTION2( ErrorTooManyWriters, "fileName=" + destImageFile->fileName() + " writerCount=" + toString( destImageFile->writerCount() ) + " readerCount=" + toString( destImageFile->readerCount() ) ); } if ( destImageFile->readerCount() > 0 ) { - throw E57_EXCEPTION2( E57_ERROR_TOO_MANY_READERS, + throw E57_EXCEPTION2( ErrorTooManyReaders, "fileName=" + destImageFile->fileName() + " writerCount=" + toString( destImageFile->writerCount() ) + " readerCount=" + toString( destImageFile->readerCount() ) ); } - /// sbufs can't be empty + // sbufs can't be empty if ( sbufs.empty() ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_API_ARGUMENT, "fileName=" + destImageFile->fileName() ); + throw E57_EXCEPTION2( ErrorBadAPIArgument, "fileName=" + destImageFile->fileName() ); } if ( !destImageFile->isWriter() ) { - throw E57_EXCEPTION2( E57_ERROR_FILE_IS_READ_ONLY, "fileName=" + destImageFile->fileName() ); + throw E57_EXCEPTION2( ErrorFileReadOnly, "fileName=" + destImageFile->fileName() ); } if ( !isAttached() ) { - throw E57_EXCEPTION2( E57_ERROR_NODE_UNATTACHED, "fileName=" + destImageFile->fileName() ); + throw E57_EXCEPTION2( ErrorNodeUnattached, "fileName=" + destImageFile->fileName() ); } - /// Get pointer to me (really shared_ptr) + // Get pointer to me (really shared_ptr) NodeImplSharedPtr ni( shared_from_this() ); - /// Downcast pointer to right type - std::shared_ptr cai( std::static_pointer_cast( ni ) ); + // Downcast pointer to right type + std::shared_ptr cai( + std::static_pointer_cast( ni ) ); - /// Return a shared_ptr to new object - std::shared_ptr cvwi( new CompressedVectorWriterImpl( cai, sbufs ) ); + // Return a shared_ptr to new object + std::shared_ptr cvwi( + new CompressedVectorWriterImpl( cai, sbufs ) ); return ( cvwi ); } - std::shared_ptr CompressedVectorNodeImpl::reader( std::vector dbufs ) + std::shared_ptr CompressedVectorNodeImpl::reader( + std::vector dbufs ) { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); ImageFileImplSharedPtr destImageFile( destImageFile_ ); - /// Check don't have any writers/readers open for this ImageFile + // Check don't have any writers/readers open for this ImageFile if ( destImageFile->writerCount() > 0 ) { - throw E57_EXCEPTION2( E57_ERROR_TOO_MANY_WRITERS, + throw E57_EXCEPTION2( ErrorTooManyWriters, "fileName=" + destImageFile->fileName() + " writerCount=" + toString( destImageFile->writerCount() ) + " readerCount=" + toString( destImageFile->readerCount() ) ); } if ( destImageFile->readerCount() > 0 ) { - throw E57_EXCEPTION2( E57_ERROR_TOO_MANY_READERS, + throw E57_EXCEPTION2( ErrorTooManyReaders, "fileName=" + destImageFile->fileName() + " writerCount=" + toString( destImageFile->writerCount() ) + " readerCount=" + toString( destImageFile->readerCount() ) ); } - /// dbufs can't be empty + // dbufs can't be empty if ( dbufs.empty() ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_API_ARGUMENT, "fileName=" + destImageFile->fileName() ); + throw E57_EXCEPTION2( ErrorBadAPIArgument, "fileName=" + destImageFile->fileName() ); } - /// Can be read or write mode, but must be attached + // Can be read or write mode, but must be attached if ( !isAttached() ) { - throw E57_EXCEPTION2( E57_ERROR_NODE_UNATTACHED, "fileName=" + destImageFile->fileName() ); + throw E57_EXCEPTION2( ErrorNodeUnattached, "fileName=" + destImageFile->fileName() ); } - /// Get pointer to me (really shared_ptr) + // Get pointer to me (really shared_ptr) NodeImplSharedPtr ni( shared_from_this() ); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE // cout << "constructing CAReader, ni:" << std::endl; // ni->dump(4); #endif - /// Downcast pointer to right type - std::shared_ptr cai( std::static_pointer_cast( ni ) ); -#ifdef E57_MAX_VERBOSE + // Downcast pointer to right type + std::shared_ptr cai( + std::static_pointer_cast( ni ) ); +#ifdef E57_VERBOSE // cout<<"constructing CAReader, cai:"<dump(4); #endif - /// Return a shared_ptr to new object - std::shared_ptr cvri( new CompressedVectorReaderImpl( cai, dbufs ) ); + // Return a shared_ptr to new object + std::shared_ptr cvri( + new CompressedVectorReaderImpl( cai, dbufs ) ); return ( cvri ); } } diff --git a/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.h b/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.h index e80541208f226..82887bf3aa526 100644 --- a/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.h +++ b/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.h @@ -33,13 +33,14 @@ namespace e57 class CompressedVectorNodeImpl : public NodeImpl { public: - CompressedVectorNodeImpl( ImageFileImplWeakPtr destImageFile ); + explicit CompressedVectorNodeImpl( ImageFileImplWeakPtr destImageFile ); ~CompressedVectorNodeImpl() override = default; NodeType type() const override { - return E57_COMPRESSED_VECTOR; + return TypeCompressedVector; } + bool isTypeEquivalent( NodeImplSharedPtr ni ) override; bool isDefined( const ustring &pathName ) override; void setAttachedRecursive() override; @@ -64,20 +65,23 @@ namespace e57 { return ( recordCount_ ); } + uint64_t getBinarySectionLogicalStart() const { return ( binarySectionLogicalStart_ ); } + void setRecordCount( int64_t recordCount ) { recordCount_ = recordCount; } + void setBinarySectionLogicalStart( uint64_t binarySectionLogicalStart ) { binarySectionLogicalStart_ = binarySectionLogicalStart; } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif diff --git a/src/3rdParty/libE57Format/src/CompressedVectorReader.cpp b/src/3rdParty/libE57Format/src/CompressedVectorReader.cpp new file mode 100644 index 0000000000000..b55787b244bd9 --- /dev/null +++ b/src/3rdParty/libE57Format/src/CompressedVectorReader.cpp @@ -0,0 +1,356 @@ +/* + * CompressedVectorReader.cpp - implementation of public functions of the + * CompressedVectorReader class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file CompressedVectorReader.cpp + +#include "CompressedVectorReaderImpl.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/*! +@brief Check whether CompressedVectorReader class invariant is true + +@details +This function checks at least the assertions in the documented class invariant description (see +class reference page for this object). Other internal invariants that are implementation-dependent +may also be checked. If any invariant clause is violated, an ::ErrorInvarianceViolation E57Exception +is thrown. + +@post No visible state is modified. +*/ +void CompressedVectorReader::checkInvariant( bool /*doRecurse*/ ) +{ + // If this CompressedVectorReader is not open, can't test invariant (almost + // every call would throw) + if ( !isOpen() ) + { + return; + } + + CompressedVectorNode cv = compressedVectorNode(); + ImageFile imf = cv.destImageFile(); + + // If destImageFile not open, can't test invariant (almost every call would + // throw) + if ( !imf.isOpen() ) + { + return; + } + + // Associated CompressedVectorNode must be attached to ImageFile + if ( !cv.isAttached() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Dest ImageFile must have at least 1 reader (this one) + if ( imf.readerCount() < 1 ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Dest ImageFile can't have any writers + if ( imf.writerCount() != 0 ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } +} + +/*! +@class e57::CompressedVectorReader + +@brief An iterator object keeping track of a read in progress from a CompressedVectorNode. + +@details +A CompressedVectorReader object is a block iterator that reads blocks of records from a +CompressedVectorNode and stores them in memory buffers (SourceDestBuffers). Blocks of records are +processed rather than a single record-at-a-time for efficiency reasons. The CompressedVectorReader +class encapsulates all the state that must be saved in between the processing of one record block +and the next (e.g. partially read disk pages, or data decompression state). New memory buffers can +be used for each record block read, or the previous buffers can be reused. + +CompressedVectorReader objects have an open/closed state. Initially a newly created +CompressedVectorReader is in the open state. After the API user calls CompressedVectorReader::close, +the object will be in the closed state and no more data transfers will be possible. + +There is no CompressedVectorReader constructor in the API. The function CompressedVectorNode::reader +returns an already constructed CompressedVectorReader object with given memory buffers +(SourceDestBuffers) already associated. + +It is recommended to call CompressedVectorReader::close to gracefully end the transfer. Unlike the +CompressedVectorWriter, not all fields in the record of the CompressedVectorNode are required to be +read at one time. + +@section CompressedVectorReader_invariant Class Invariant +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude CompressedVectorReader.cpp +@skip void CompressedVectorReader::checkInvariant +@until ^} + +@see CompressedVectorNode, CompressedVectorWriter +*/ + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +CompressedVectorReader::CompressedVectorReader( std::shared_ptr ni ) : + impl_( ni ) +{ +} +/// @endcond + +/*! +@brief Request transfer of blocks of data from CompressedVectorNode into +previously designated destination buffers. + +@details +The SourceDestBuffers used are previously designated either in +CompressedVectorNode::reader where this object was created, or in the last call +to CompressedVectorReader::read(std::vector&) where new +buffers were designated. The function will always return the full number of +records requested (the capacity of the SourceDestBuffers) unless it has reached +the end of the CompressedVectorNode, in which case it will return less than the +capacity of the SourceDestBuffers. Partial reads will store the records at the +beginning of the SourceDestBuffers. It is not an error to call this function +after all records in the CompressedVectorNode have been read (the function +returns 0). + +If a conversion or bounds error occurs during the transfer, the +CompressedVectorReader is left in an undocumented state (it can't be used any +further). If a file I/O or checksum error occurs during the transfer, both the +CompressedVectorReader and the associated ImageFile are left in an undocumented +state (they can't be used any further). + +The API user is responsible for ensuring that the underlying memory buffers +represented in the SourceDestBuffers still exist when this function is called. +The E57 Foundation Implementation cannot detect that a memory buffer been +destroyed. + +@pre The associated ImageFile must be open. +@pre This CompressedVectorReader must be open (i.e isOpen()) + +@return The number of records read. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorReaderNotOpen +@throw ::ErrorConversionRequired This CompressedVectorReader +in undocumented state +@throw ::ErrorValueNotRepresentable This CompressedVectorReader +in undocumented state +@throw ::ErrorScaledValueNotRepresentable This CompressedVectorReader +in undocumented state +@throw ::ErrorReal64TooLarge This CompressedVectorReader +in undocumented state +@throw ::ErrorExpectingNumeric This CompressedVectorReader +in undocumented state +@throw ::ErrorExpectingUString This CompressedVectorReader +in undocumented state +@throw ::ErrorBadCVPacket This CompressedVectorReader, associated +ImageFile in undocumented state +@throw ::ErrorSeekFailed This CompressedVectorReader, associated +ImageFile in undocumented state +@throw ::ErrorReadFailed This CompressedVectorReader, associated +ImageFile in undocumented state +@throw ::ErrorBadChecksum This CompressedVectorReader, associated +ImageFile in undocumented state +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorReader::read(std::vector&), +CompressedVectorNode::reader, SourceDestBuffer, +CompressedVectorReader::read(std::vector&) +*/ +unsigned CompressedVectorReader::read() +{ + return impl_->read(); +} + +/*! +@brief Request transfer of block of data from CompressedVectorNode into given destination buffers. + +@param [in] dbufs Vector of memory buffers that will receive data read from a CompressedVectorNode. + +@details +The @a dbufs must all have the same capacity. + +The specified @a dbufs must have same number of elements as previously designated SourceDestBuffer +vector. The each SourceDestBuffer within @a dbufs must be identical to the previously designated +SourceDestBuffer except for capacity and buffer address. + +The @a dbufs locations are saved so that a later call to CompressedVectorReader::read() can be used +without having to re-specify the SourceDestBuffers. + +The function will always return the full number of records requested (the capacity of the +SourceDestBuffers) unless it has reached the end of the CompressedVectorNode, in which case it will +return less than the capacity of the SourceDestBuffers. Partial reads will store the records at the +beginning of the SourceDestBuffers. It is not an error to call this function after all records in +the CompressedVectorNode have been read (the function returns 0). + +If a conversion or bounds error occurs during the transfer, the CompressedVectorReader is left in an +undocumented state (it can't be used any further). If a file I/O or checksum error occurs during the +transfer, both the CompressedVectorReader and the associated ImageFile are left in an undocumented +state (they can't be used any further). + +The API user is responsible for ensuring that the underlying memory buffers represented in the +SourceDestBuffers still exist when this function is called. The E57 Foundation Implementation cannot +detect that a memory buffer been destroyed. + +@pre The associated ImageFile must be open. +@pre This CompressedVectorReader must be open (i.e isOpen()) + +@return The number of records read. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorReaderNotOpen +@throw ::ErrorPathUndefined +@throw ::ErrorBufferSizeMismatch +@throw ::ErrorBufferDuplicatePathName +@throw ::ErrorConversionRequired This CompressedVectorReader in undocumented state +@throw ::ErrorValueNotRepresentable This CompressedVectorReader in undocumented state +@throw ::ErrorScaledValueNotRepresentable This CompressedVectorReader in undocumented state +@throw ::ErrorReal64TooLarge This CompressedVectorReader in undocumented state +@throw ::ErrorExpectingNumeric This CompressedVectorReader in undocumented state +@throw ::ErrorExpectingUString This CompressedVectorReader in undocumented state +@throw ::ErrorBadCVPacket This CompressedVectorReader, associated ImageFile in undocumented state +@throw ::ErrorSeekFailed This CompressedVectorReader, associated ImageFile in undocumented state +@throw ::ErrorReadFailed This CompressedVectorReader, associated ImageFile in undocumented state +@throw ::ErrorBadChecksum This CompressedVectorReader, associated ImageFile in undocumented state +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorReader::read(), CompressedVectorNode::reader, SourceDestBuffer +*/ +unsigned CompressedVectorReader::read( std::vector &dbufs ) +{ + return impl_->read( dbufs ); +} + +/*! +@brief Set record number of CompressedVectorNode where next read will start. + +@param [in] recordNumber The index of record in CompressedVectorNode where next read using this +CompressedVectorReader will start. + +@details +This function may be called at any time (as long as ImageFile and CompressedVectorReader are open). +The next read will start at the given recordNumber. It is not an error to seek to recordNumber = +childCount() (i.e. to one record past end of CompressedVectorNode). + +@pre @a recordNumber <= childCount() of CompressedVectorNode. +@pre The associated ImageFile must be open. +@pre This CompressedVectorReader must be open (i.e isOpen()) + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorReaderNotOpen +@throw ::ErrorBadCVPacket +@throw ::ErrorSeekFailed +@throw ::ErrorReadFailed +@throw ::ErrorBadChecksum +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorNode::reader +*/ +void CompressedVectorReader::seek( int64_t recordNumber ) +{ + impl_->seek( recordNumber ); +} + +/*! +@brief End the read operation. + +@details +It is recommended that this function be called to gracefully end a transfer to a +CompressedVectorNode. It is not an error to call this function if the CompressedVectorReader is +already closed. This function will cause the CompressedVectorReader to enter the closed state, and +any further transfers requests will fail. + +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorReader::isOpen, CompressedVectorNode::reader +*/ +void CompressedVectorReader::close() +{ + impl_->close(); +} + +/*! +@brief Test whether CompressedVectorReader is still open for reading. + +@pre The associated ImageFile must be open. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorReader::close, CompressedVectorNode::reader +*/ +bool CompressedVectorReader::isOpen() +{ + return impl_->isOpen(); +} + +/*! +@brief Return the CompressedVectorNode being read. + +@details +It is not an error if this CompressedVectorReader is closed. + +@pre The associated ImageFile must be open. + +@return A smart CompressedVectorNode handle referencing the underlying object being read from. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorReader::close, CompressedVectorNode::reader +*/ +CompressedVectorNode CompressedVectorReader::compressedVectorNode() const +{ + return impl_->compressedVectorNode(); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void CompressedVectorReader::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void CompressedVectorReader::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif diff --git a/src/3rdParty/libE57Format/src/CompressedVectorReaderImpl.cpp b/src/3rdParty/libE57Format/src/CompressedVectorReaderImpl.cpp index 87fe47bae01f6..ff3ac52fa8f81 100644 --- a/src/3rdParty/libE57Format/src/CompressedVectorReaderImpl.cpp +++ b/src/3rdParty/libE57Format/src/CompressedVectorReaderImpl.cpp @@ -32,55 +32,58 @@ #include "Packet.h" #include "SectionHeaders.h" #include "SourceDestBufferImpl.h" +#include "StringFunctions.h" namespace e57 { - CompressedVectorReaderImpl::CompressedVectorReaderImpl( std::shared_ptr cvi, - std::vector &dbufs ) : + CompressedVectorReaderImpl::CompressedVectorReaderImpl( + std::shared_ptr cvi, + std::vector &dbufs ) : isOpen_( false ), // set to true when succeed below cVector_( cvi ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "CompressedVectorReaderImpl() called" << std::endl; //??? #endif checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - /// Allow reading of a completed CompressedVector, whether file is being read - /// or currently being written. - ///??? what other situations need checking for? - ///??? check if CV not yet written to? - ///??? file in error state? + // Allow reading of a completed CompressedVector, whether file is being read + // or currently being written. + //??? what other situations need checking for? + //??? check if CV not yet written to? + //??? file in error state? - /// Empty dbufs is an error + // Empty dbufs is an error if ( dbufs.empty() ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_API_ARGUMENT, - "imageFileName=" + cVector_->imageFileName() + " cvPathName=" + cVector_->pathName() ); + throw E57_EXCEPTION2( ErrorBadAPIArgument, "imageFileName=" + cVector_->imageFileName() + + " cvPathName=" + cVector_->pathName() ); } - /// Get CompressedArray's prototype node (all array elements must match this - /// type) + // Get CompressedArray's prototype node (all array elements must match this + // type) proto_ = cVector_->getPrototype(); - /// Check dbufs well formed (matches proto exactly) + // Check dbufs well formed (matches proto exactly) setBuffers( dbufs ); - /// For each dbuf, create an appropriate Decoder based on the cVector_ - /// attributes + // For each dbuf, create an appropriate Decoder based on the cVector_ + // attributes for ( unsigned i = 0; i < dbufs_.size(); i++ ) { std::vector theDbuf; theDbuf.push_back( dbufs.at( i ) ); - std::shared_ptr decoder = Decoder::DecoderFactory( i, cVector_.get(), theDbuf, ustring() ); + std::shared_ptr decoder = + Decoder::DecoderFactory( i, cVector_.get(), theDbuf, ustring() ); - /// Calc which stream the given path belongs to. This depends on position - /// of the node in the proto tree. + // Calc which stream the given path belongs to. This depends on position + // of the node in the proto tree. NodeImplSharedPtr readNode = proto_->get( dbufs.at( i ).pathName() ); uint64_t bytestreamNumber = 0; if ( !proto_->findTerminalPosition( readNode, bytestreamNumber ) ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "dbufIndex=" + toString( i ) ); + throw E57_EXCEPTION2( ErrorInternal, "dbufIndex=" + toString( i ) ); } channels_.emplace_back( dbufs.at( i ), decoder, static_cast( bytestreamNumber ), @@ -89,7 +92,7 @@ namespace e57 recordCount_ = 0; - /// Get how many records are actually defined + // Get how many records are actually defined maxRecordCount_ = cvi->childCount(); ImageFileImplSharedPtr imf( cVector_->destImageFile_ ); @@ -97,7 +100,7 @@ namespace e57 //??? what if fault in this constructor? cache_ = new PacketReadCache( imf->file_, 32 ); - /// Read CompressedVector section header + // Read CompressedVector section header CompressedVectorSectionHeader sectionHeader; uint64_t sectionLogicalStart = cVector_->getBinarySectionLogicalStart(); if ( sectionLogicalStart == 0 ) @@ -105,56 +108,59 @@ namespace e57 //??? should have caught this before got here, in XML read, get this if CV // wasn't written to // by writer. - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, - "imageFileName=" + cVector_->imageFileName() + " cvPathName=" + cVector_->pathName() ); + throw E57_EXCEPTION2( ErrorInternal, "imageFileName=" + cVector_->imageFileName() + + " cvPathName=" + cVector_->pathName() ); } imf->file_->seek( sectionLogicalStart, CheckedFile::Logical ); imf->file_->read( reinterpret_cast( §ionHeader ), sizeof( sectionHeader ) ); -#ifdef E57_DEBUG +#if VALIDATE_BASIC sectionHeader.verify( imf->file_->length( CheckedFile::Physical ) ); #endif - /// Pre-calc end of section, so can tell when we are out of packets. + // Pre-calc end of section, so can tell when we are out of packets. sectionEndLogicalOffset_ = sectionLogicalStart + sectionHeader.sectionLogicalLength; - /// Convert physical offset to first data packet to logical - uint64_t dataLogicalOffset = imf->file_->physicalToLogical( sectionHeader.dataPhysicalOffset ); + // Convert physical offset to first data packet to logical + uint64_t dataLogicalOffset = + imf->file_->physicalToLogical( sectionHeader.dataPhysicalOffset ); - /// Verify that packet given by dataPhysicalOffset is actually a data packet, - /// init channels + // Verify that packet given by dataPhysicalOffset is actually a data packet, + // init channels { char *anyPacket = nullptr; std::unique_ptr packetLock = cache_->lock( dataLogicalOffset, anyPacket ); auto dpkt = reinterpret_cast( anyPacket ); - /// Double check that have a data packet + // Double check that have a data packet if ( dpkt->header.packetType != DATA_PACKET ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetType=" + toString( dpkt->header.packetType ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, + "packetType=" + toString( dpkt->header.packetType ) ); } - /// Have good packet, initialize channels + // Have good packet, initialize channels for ( auto &channel : channels_ ) { channel.currentPacketLogicalOffset = dataLogicalOffset; channel.currentBytestreamBufferIndex = 0; - channel.currentBytestreamBufferLength = dpkt->getBytestreamBufferLength( channel.bytestreamNumber ); + channel.currentBytestreamBufferLength = + dpkt->getBytestreamBufferLength( channel.bytestreamNumber ); } } - /// Just before return (and can't throw) increment reader count ??? safer - /// way to assure don't miss close? + // Just before return (and can't throw) increment reader count ??? safer + // way to assure don't miss close? imf->incrReaderCount(); - /// If get here, the reader is open + // If get here, the reader is open isOpen_ = true; } CompressedVectorReaderImpl::~CompressedVectorReaderImpl() { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "~CompressedVectorReaderImpl() called" << std::endl; //??? // dump(4); #endif @@ -163,7 +169,7 @@ namespace e57 { try { - close(); ///??? what if already closed? + close(); //??? what if already closed? } catch ( ... ) { @@ -174,27 +180,28 @@ namespace e57 void CompressedVectorReaderImpl::setBuffers( std::vector &dbufs ) { - /// don't checkImageFileOpen - /// don't checkReaderOpen + // don't checkImageFileOpen + // don't checkReaderOpen - /// Check dbufs well formed: no dups, no extra, missing is ok + // Check dbufs well formed: no dups, no extra, missing is ok proto_->checkBuffers( dbufs, true ); - /// If had previous dbufs_, check to see if new ones have changed in - /// incompatible way + // If had previous dbufs_, check to see if new ones have changed in + // incompatible way if ( !dbufs_.empty() ) { if ( dbufs_.size() != dbufs.size() ) { - throw E57_EXCEPTION2( E57_ERROR_BUFFERS_NOT_COMPATIBLE, - "oldSize=" + toString( dbufs_.size() ) + " newSize=" + toString( dbufs.size() ) ); + throw E57_EXCEPTION2( ErrorBuffersNotCompatible, + "oldSize=" + toString( dbufs_.size() ) + + " newSize=" + toString( dbufs.size() ) ); } for ( size_t i = 0; i < dbufs_.size(); i++ ) { std::shared_ptr oldBuf = dbufs_[i].impl(); std::shared_ptr newBuf = dbufs[i].impl(); - /// Throw exception if old and new not compatible + // Throw exception if old and new not compatible oldBuf->checkCompatible( newBuf ); } } @@ -204,12 +211,12 @@ namespace e57 unsigned CompressedVectorReaderImpl::read( std::vector &dbufs ) { - /// don't checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__), read() will - /// do it + // don't checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__), read() will + // do it checkReaderOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - /// Check compatible with current dbufs + // Check compatible with current dbufs setBuffers( dbufs ); return ( read() ); @@ -217,46 +224,46 @@ namespace e57 unsigned CompressedVectorReaderImpl::read() { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "CompressedVectorReaderImpl::read() called" << std::endl; //??? #endif checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); checkReaderOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - /// Rewind all dbufs so start writing to them at beginning + // Rewind all dbufs so start writing to them at beginning for ( auto &dbuf : dbufs_ ) { dbuf.impl()->rewind(); } - /// Allow decoders to use data they already have in their queue to fill newly - /// empty dbufs This helps to keep decoder input queues smaller, which - /// reduces backtracking in the packet cache. + // Allow decoders to use data they already have in their queue to fill newly + // empty dbufs This helps to keep decoder input queues smaller, which + // reduces backtracking in the packet cache. for ( auto &channel : channels_ ) { channel.decoder->inputProcess( nullptr, 0 ); } - /// Loop until every dbuf is full or we have reached end of the binary - /// section. + // Loop until every dbuf is full or we have reached end of the binary + // section. while ( true ) { - /// Find the earliest packet position for channels that are still hungry - /// It's important to call inputProcess of the decoders before this call, - /// so current hungriness level is reflected. + // Find the earliest packet position for channels that are still hungry + // It's important to call inputProcess of the decoders before this call, + // so current hungriness level is reflected. uint64_t earliestPacketLogicalOffset = earliestPacketNeededForInput(); - /// If nobody's hungry, we are done with the read - if ( earliestPacketLogicalOffset == E57_UINT64_MAX ) + // If nobody's hungry, we are done with the read + if ( earliestPacketLogicalOffset == UINT64_MAX ) { break; } - /// Feed packet to the hungry decoders + // Feed packet to the hungry decoders feedPacketToDecoders( earliestPacketLogicalOffset ); } - /// Verify that each channel produced the same number of records + // Verify that each channel produced the same number of records unsigned outputCount = 0; for ( unsigned i = 0; i < channels_.size(); i++ ) { @@ -269,20 +276,21 @@ namespace e57 { if ( outputCount != chan->dbuf.impl()->nextIndex() ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "outputCount=" + toString( outputCount ) + " nextIndex=" + - toString( chan->dbuf.impl()->nextIndex() ) ); + throw E57_EXCEPTION2( + ErrorInternal, "outputCount=" + toString( outputCount ) + + " nextIndex=" + toString( chan->dbuf.impl()->nextIndex() ) ); } } } - /// Return number of records transferred to each dbuf. + // Return number of records transferred to each dbuf. return outputCount; } uint64_t CompressedVectorReaderImpl::earliestPacketNeededForInput() const { - uint64_t earliestPacketLogicalOffset = E57_UINT64_MAX; -#ifdef E57_MAX_VERBOSE + uint64_t earliestPacketLogicalOffset = UINT64_MAX; +#ifdef E57_VERBOSE unsigned earliestChannel = 0; #endif @@ -290,29 +298,29 @@ namespace e57 { const DecodeChannel *chan = &channels_[i]; - /// Test if channel needs more input. - /// Important to call inputProcess just before this, so these tests work. + // Test if channel needs more input. + // Important to call inputProcess just before this, so these tests work. if ( !chan->isOutputBlocked() && !chan->inputFinished ) { - /// Check if earliest so far + // Check if earliest so far if ( chan->currentPacketLogicalOffset < earliestPacketLogicalOffset ) { earliestPacketLogicalOffset = chan->currentPacketLogicalOffset; -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE earliestChannel = i; #endif } } } -#ifdef E57_MAX_VERBOSE - if ( earliestPacketLogicalOffset == E57_UINT64_MAX ) +#ifdef E57_VERBOSE + if ( earliestPacketLogicalOffset == UINT64_MAX ) { std::cout << "earliestPacketNeededForInput returning none found" << std::endl; } else { - std::cout << "earliestPacketNeededForInput returning " << earliestPacketLogicalOffset << " for channel[" - << earliestChannel << "]" << std::endl; + std::cout << "earliestPacketNeededForInput returning " << earliestPacketLogicalOffset + << " for channel[" << earliestChannel << "]" << std::endl; } #endif return earliestPacketLogicalOffset; @@ -327,9 +335,11 @@ namespace e57 return reinterpret_cast( packet ); } - inline bool _alreadyReadPacket( const DecodeChannel &channel, uint64_t currentPacketLogicalOffset ) + inline bool _alreadyReadPacket( const DecodeChannel &channel, + uint64_t currentPacketLogicalOffset ) { - return ( ( channel.currentPacketLogicalOffset != currentPacketLogicalOffset ) || channel.isOutputBlocked() ); + return ( ( channel.currentPacketLogicalOffset != currentPacketLogicalOffset ) || + channel.isOutputBlocked() ); } void CompressedVectorReaderImpl::feedPacketToDecoders( uint64_t currentPacketLogicalOffset ) @@ -337,21 +347,18 @@ namespace e57 // Get packet at currentPacketLogicalOffset into memory. auto dpkt = dataPacket( currentPacketLogicalOffset ); - // Double check that have a data packet. Should have already determined - // this. + // Double check that have a data packet. Should have already determined this. if ( dpkt->header.packetType != DATA_PACKET ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "packetType=" + toString( dpkt->header.packetType ) ); + throw E57_EXCEPTION2( ErrorInternal, "packetType=" + toString( dpkt->header.packetType ) ); } - // Read earliest packet into cache and send data to decoders with unblocked - // output + // Read earliest packet into cache and send data to decoders with unblocked output bool anyChannelHasExhaustedPacket = false; - uint64_t nextPacketLogicalOffset = E57_UINT64_MAX; + uint64_t nextPacketLogicalOffset = UINT64_MAX; - // Feed bytestreams to channels with unblocked output that are reading from - // this packet + // Feed bytestreams to channels with unblocked output that are reading from this packet for ( DecodeChannel &channel : channels_ ) { // Skip channels that have already read this packet. @@ -367,9 +374,10 @@ namespace e57 // Double check we are not off end of buffer if ( channel.currentBytestreamBufferIndex > bsbLength ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, - "currentBytestreamBufferIndex =" + toString( channel.currentBytestreamBufferIndex ) + - " bsbLength=" + toString( bsbLength ) ); + throw E57_EXCEPTION2( + ErrorInternal, + "currentBytestreamBufferIndex =" + toString( channel.currentBytestreamBufferIndex ) + + " bsbLength=" + toString( bsbLength ) ); } // Calc where we are in the buffer @@ -378,23 +386,24 @@ namespace e57 if ( &uneatenStart[uneatenLength] > &bsbStart[bsbLength] ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "uneatenLength=" + toString( uneatenLength ) + - " bsbLength=" + toString( bsbLength ) ); + throw E57_EXCEPTION2( ErrorInternal, "uneatenLength=" + toString( uneatenLength ) + + " bsbLength=" + toString( bsbLength ) ); } // Feed into decoder const size_t bytesProcessed = channel.decoder->inputProcess( uneatenStart, uneatenLength ); -#ifdef E57_MAX_VERBOSE - std::cout << " stream[" << channel.bytestreamNumber << "]: feeding decoder " << uneatenLength << " bytes" - << std::endl; +#ifdef E57_VERBOSE + std::cout << " stream[" << channel.bytestreamNumber << "]: feeding decoder " + << uneatenLength << " bytes" << std::endl; if ( uneatenLength == 0 ) { channel.dump( 8 ); } - std::cout << " stream[" << channel.bytestreamNumber << "]: bytesProcessed=" << bytesProcessed << std::endl; + std::cout << " stream[" << channel.bytestreamNumber + << "]: bytesProcessed=" << bytesProcessed << std::endl; #endif // Adjust counts of bytestream location @@ -404,12 +413,13 @@ namespace e57 // packet if ( channel.isInputBlocked() ) { -#ifdef E57_MAX_VERBOSE - std::cout << " stream[" << channel.bytestreamNumber << "] has exhausted its input in current packet" - << std::endl; +#ifdef E57_VERBOSE + std::cout << " stream[" << channel.bytestreamNumber + << "] has exhausted its input in current packet" << std::endl; #endif anyChannelHasExhaustedPacket = true; - nextPacketLogicalOffset = currentPacketLogicalOffset + dpkt->header.packetLogicalLengthMinus1 + 1; + nextPacketLogicalOffset = + currentPacketLogicalOffset + dpkt->header.packetLogicalLengthMinus1 + 1; } } @@ -425,7 +435,7 @@ namespace e57 // Some channel has exhausted this packet, so find next data packet and // update currentPacketLogicalOffset for all interested channels. - if ( nextPacketLogicalOffset < E57_UINT64_MAX ) + if ( nextPacketLogicalOffset < UINT64_MAX ) { //??? huh? // Get packet at nextPacketLogicalOffset into memory. dpkt = dataPacket( nextPacketLogicalOffset ); @@ -444,9 +454,10 @@ namespace e57 // It is OK if the next packet doesn't contain any data for this // channel, will skip packet on next iter of loop - channel.currentBytestreamBufferLength = dpkt->getBytestreamBufferLength( channel.bytestreamNumber ); + channel.currentBytestreamBufferLength = + dpkt->getBytestreamBufferLength( channel.bytestreamNumber ); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " set new stream buffer for channel[" << channel.bytestreamNumber << "], length=" << channel.currentBytestreamBufferLength << std::endl; #endif @@ -457,7 +468,7 @@ namespace e57 { // Reached end without finding data packet, mark exhausted channels as // finished -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " at end of data packets" << std::endl; #endif if ( nextPacketLogicalOffset >= sectionEndLogicalOffset_ ) @@ -470,8 +481,9 @@ namespace e57 continue; } -#ifdef E57_MAX_VERBOSE - std::cout << " Marking channel[" << channel.bytestreamNumber << "] as finished" << std::endl; +#ifdef E57_VERBOSE + std::cout << " Marking channel[" << channel.bytestreamNumber << "] as finished" + << std::endl; #endif channel.inputFinished = true; } @@ -481,74 +493,78 @@ namespace e57 uint64_t CompressedVectorReaderImpl::findNextDataPacket( uint64_t nextPacketLogicalOffset ) { -#ifdef E57_MAX_VERBOSE - std::cout << " searching for next data packet, nextPacketLogicalOffset=" << nextPacketLogicalOffset +#ifdef E57_VERBOSE + std::cout << " searching for next data packet, nextPacketLogicalOffset=" + << nextPacketLogicalOffset << " sectionEndLogicalOffset=" << sectionEndLogicalOffset_ << std::endl; #endif - /// Starting at nextPacketLogicalOffset, search for next data packet until - /// hit end of binary section. + // Starting at nextPacketLogicalOffset, search for next data packet until + // hit end of binary section. while ( nextPacketLogicalOffset < sectionEndLogicalOffset_ ) { char *anyPacket = nullptr; - std::unique_ptr packetLock = cache_->lock( nextPacketLogicalOffset, anyPacket ); + std::unique_ptr packetLock = + cache_->lock( nextPacketLogicalOffset, anyPacket ); - /// Guess it's a data packet, if not continue to next packet + // Guess it's a data packet, if not continue to next packet auto dpkt = reinterpret_cast( anyPacket ); if ( dpkt->header.packetType == DATA_PACKET ) { -#ifdef E57_MAX_VERBOSE - std::cout << " Found next data packet at nextPacketLogicalOffset=" << nextPacketLogicalOffset << std::endl; +#ifdef E57_VERBOSE + std::cout << " Found next data packet at nextPacketLogicalOffset=" + << nextPacketLogicalOffset << std::endl; #endif return nextPacketLogicalOffset; } - /// All packets have length in same place, so can use the field to skip to - /// next packet. + // All packets have length in same place, so can use the field to skip to + // next packet. nextPacketLogicalOffset += dpkt->header.packetLogicalLengthMinus1 + 1; } - /// Ran off end of section, so return failure code. - return E57_UINT64_MAX; + // Ran off end of section, so return failure code. + return UINT64_MAX; } void CompressedVectorReaderImpl::seek( uint64_t /*recordNumber*/ ) { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - ///!!! implement - throw E57_EXCEPTION1( E57_ERROR_NOT_IMPLEMENTED ); + // !!! implement + throw E57_EXCEPTION1( ErrorNotImplemented ); } bool CompressedVectorReaderImpl::isOpen() const { - /// don't checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__), or - /// checkReaderOpen() + // don't checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__), or + // checkReaderOpen() return ( isOpen_ ); } - std::shared_ptr CompressedVectorReaderImpl::compressedVectorNode() const + std::shared_ptr CompressedVectorReaderImpl::compressedVectorNode() + const { return ( cVector_ ); } void CompressedVectorReaderImpl::close() { - /// Before anything that can throw, decrement reader count + // Before anything that can throw, decrement reader count ImageFileImplSharedPtr imf( cVector_->destImageFile_ ); imf->decrReaderCount(); checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - /// No error if reader not open + // No error if reader not open if ( !isOpen_ ) { return; } - /// Destroy decoders + // Destroy decoders channels_.clear(); delete cache_; @@ -561,7 +577,9 @@ namespace e57 const char *srcFunctionName ) const { // unimplemented... - (void)srcFileName; (void)srcLineNumber; (void)srcFunctionName; + UNUSED( srcFileName ); + UNUSED( srcLineNumber ); + UNUSED( srcFunctionName ); } void CompressedVectorReaderImpl::checkReaderOpen( const char *srcFileName, int srcLineNumber, @@ -569,13 +587,14 @@ namespace e57 { if ( !isOpen_ ) { - throw E57Exception( E57_ERROR_READER_NOT_OPEN, - "imageFileName=" + cVector_->imageFileName() + " cvPathName=" + cVector_->pathName(), + throw E57Exception( ErrorReaderNotOpen, + "imageFileName=" + cVector_->imageFileName() + + " cvPathName=" + cVector_->pathName(), srcFileName, srcLineNumber, srcFunctionName ); } } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void CompressedVectorReaderImpl::dump( int indent, std::ostream &os ) { os << space( indent ) << "isOpen:" << isOpen_ << std::endl; diff --git a/src/3rdParty/libE57Format/src/CompressedVectorReaderImpl.h b/src/3rdParty/libE57Format/src/CompressedVectorReaderImpl.h index 7e289ae9da188..3064bc1678bbe 100644 --- a/src/3rdParty/libE57Format/src/CompressedVectorReaderImpl.h +++ b/src/3rdParty/libE57Format/src/CompressedVectorReaderImpl.h @@ -36,8 +36,10 @@ namespace e57 class CompressedVectorReaderImpl { public: - CompressedVectorReaderImpl( std::shared_ptr ni, std::vector &dbufs ); + CompressedVectorReaderImpl( std::shared_ptr cvi, + std::vector &dbufs ); ~CompressedVectorReaderImpl(); + unsigned read(); unsigned read( std::vector &dbufs ); void seek( uint64_t recordNumber ); @@ -45,13 +47,15 @@ namespace e57 std::shared_ptr compressedVectorNode() const; void close(); -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ); #endif private: - void checkImageFileOpen( const char *srcFileName, int srcLineNumber, const char *srcFunctionName ) const; - void checkReaderOpen( const char *srcFileName, int srcLineNumber, const char *srcFunctionName ) const; + void checkImageFileOpen( const char *srcFileName, int srcLineNumber, + const char *srcFunctionName ) const; + void checkReaderOpen( const char *srcFileName, int srcLineNumber, + const char *srcFunctionName ) const; void setBuffers( std::vector &dbufs ); //???needed? uint64_t earliestPacketNeededForInput() const; diff --git a/src/3rdParty/libE57Format/src/CompressedVectorWriter.cpp b/src/3rdParty/libE57Format/src/CompressedVectorWriter.cpp new file mode 100644 index 0000000000000..e994b3f040f7d --- /dev/null +++ b/src/3rdParty/libE57Format/src/CompressedVectorWriter.cpp @@ -0,0 +1,333 @@ +/* + * CompressedVectorWriter.cpp - implementation of public functions of the + * CompressedVectorWriter class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file CompressedVectorWriter.cpp + +#include "CompressedVectorWriterImpl.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/*! +@brief Check whether CompressedVectorWriter class invariant is true +@copydetails CompressedVectorReader::checkInvariant +*/ +void CompressedVectorWriter::checkInvariant( bool /*doRecurse*/ ) +{ + // If this CompressedVectorWriter is not open, can't test invariant (almost + // every call would throw) + if ( !isOpen() ) + { + return; + } + + CompressedVectorNode cv = compressedVectorNode(); + ImageFile imf = cv.destImageFile(); + + // If destImageFile not open, can't test invariant (almost every call would + // throw) + if ( !imf.isOpen() ) + { + return; + } + + // Associated CompressedVectorNode must be attached to ImageFile + if ( !cv.isAttached() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Dest ImageFile must be writable + if ( !imf.isWritable() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Dest ImageFile must have exactly 1 writer (this one) + if ( imf.writerCount() != 1 ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Dest ImageFile can't have any readers + if ( imf.readerCount() != 0 ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } +} + +/*! +@class e57::CompressedVectorWriter + +@brief An iterator object keeping track of a write in progress to a CompressedVectorNode. + +@details +A CompressedVectorWriter object is a block iterator that reads blocks of records from memory and +stores them in a CompressedVectorNode. Blocks of records are processed rather than a single +record-at-a-time for efficiency reasons. The CompressedVectorWriter class encapsulates all the state +that must be saved in between the processing of one record block and the next (e.g. partially +written disk pages, partially filled bytes in a bytestream, or data compression state). New memory +buffers can be used for each record block write, or the previous buffers can be reused. + +CompressedVectorWriter objects have an open/closed state. Initially a newly created +CompressedVectorWriter is in the open state. After the API user calls CompressedVectorWriter::close, +the object will be in the closed state and no more data transfers will be possible. + +There is no CompressedVectorWriter constructor in the API. The function CompressedVectorNode::writer +returns an already constructed CompressedVectorWriter object with given memory buffers +(SourceDestBuffers) already associated. CompressedVectorWriter::close must explicitly be called to +safely and gracefully end the transfer. + +@warning If CompressedVectorWriter::close is not called before the CompressedVectorWriter destructor +is invoked, all writes to the CompressedVectorNode will be lost (it will have zero children). + +@section CompressedVectorWriter_invariant Class Invariant A class invariant is a list of statements +about an object that are always true before and after any operation on the object. An invariant is +useful for testing correct operation of an implementation. Statements in an invariant can involve +only externally visible state, or can refer to internal implementation-specific state that is not +visible to the API user. The following C++ code checks externally visible state for consistency and +throws an exception if the invariant is violated: + +@dontinclude CompressedVectorWriter.cpp +@skip void CompressedVectorWriter::checkInvariant +@until ^} + +@see CompressedVectorNode, CompressedVectorReader +*/ + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +CompressedVectorWriter::CompressedVectorWriter( std::shared_ptr ni ) : + impl_( ni ) +{ +} +/// @endcond + +/*! +@brief Request transfer of blocks of data to CompressedVectorNode from previously designated source +buffers. + +@param [in] recordCount Number of records to write. + +@details +The SourceDestBuffers used are previously designated either in CompressedVectorNode::writer where +this object was created, or in the last call to +CompressedVectorWriter::write(std::vector&, unsigned) where new buffers were +designated. + +If a conversion or bounds error occurs during the transfer, the CompressedVectorWriter is left in an +undocumented state (it can't be used any further), and all previously written records are deleted +from the associated CompressedVectorNode which will then have zero children. If a file I/O or +checksum error occurs during the transfer, both this CompressedVectorWriter and the associated +ImageFile are left in an undocumented state (they can't be used any further). If +CompressedVectorWriter::close is not called before the CompressedVectorWriter destructor is invoked, +all writes to the CompressedVectorNode will be lost (it will have zero children). + +@pre The associated ImageFile must be open. +@pre This CompressedVectorWriter must be open (i.e isOpen()) + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorWriterNotOpen +@throw ::ErrorPathUndefined +@throw ::ErrorNoBufferForElement +@throw ::ErrorBufferSizeMismatch +@throw ::ErrorBufferDuplicatePathName +@throw ::ErrorConversionRequired This CompressedVectorWriter in undocumented state, associated +CompressedVectorNode modified but consistent, associated ImageFile modified but consistent. +@throw ::ErrorValueOutOfBounds This CompressedVectorWriter in undocumented state, associated +CompressedVectorNode modified but consistent, associated ImageFile modified but consistent. +@throw ::ErrorValueNotRepresentable This CompressedVectorWriter in undocumented state, associated +CompressedVectorNode modified but consistent, associated ImageFile modified but consistent. +@throw ::ErrorScaledValueNotRepresentable This CompressedVectorWriter in undocumented state, +associated CompressedVectorNode modified but consistent, associated ImageFile modified but +consistent. +@throw ::ErrorReal64TooLarge This CompressedVectorWriter in undocumented state, associated +CompressedVectorNode modified but consistent, associated ImageFile modified but consistent. +@throw ::ErrorExpectingNumeric This CompressedVectorWriter in undocumented state, associated +CompressedVectorNode modified but consistent, associated ImageFile modified but consistent. +@throw ::ErrorExpectingUString This CompressedVectorWriter in undocumented state, associated +CompressedVectorNode modified but consistent, associated ImageFile modified but consistent. +@throw ::ErrorSeekFailed This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorReadFailed This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorWriteFailed This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorBadChecksum This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorWriter::write(std::vector&,unsigned), +CompressedVectorNode::writer, CompressedVectorWriter::close, SourceDestBuffer, E57Exception +*/ +void CompressedVectorWriter::write( const size_t recordCount ) +{ + impl_->write( recordCount ); +} + +/*! +@brief Request transfer of block of data to CompressedVectorNode from given source buffers. + +@param [in] sbufs Vector of memory buffers that hold data to be written to a CompressedVectorNode. +@param [in] recordCount Number of records to write. + +@details +The @a sbufs must all have the same capacity. + +The @a sbufs capacity must be >= @a recordCount. + +The specified @a sbufs must have same number of elements as previously designated SourceDestBuffer +vector. The each SourceDestBuffer within @a sbufs must be identical to the previously designated +SourceDestBuffer except for capacity and buffer address. + +The @a sbufs locations are saved so that a later call to CompressedVectorWriter::write(unsigned) can +be used without having to re-specify the SourceDestBuffers. + +If a conversion or bounds error occurs during the transfer, the CompressedVectorWriter is left in an +undocumented state (it can't be used any further), and all previously written records are deleted +from the the associated CompressedVectorNode which will then have zero children. If a file I/O or +checksum error occurs during the transfer, both this CompressedVectorWriter and the associated +ImageFile are left in an undocumented state (they can't be used any further). + +@warning If CompressedVectorWriter::close is not called before the CompressedVectorWriter destructor +is invoked, all writes to the CompressedVectorNode will be lost (it will have zero children). + +@pre The associated ImageFile must be open. +@pre This CompressedVectorWriter must be open (i.e isOpen()) + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorWriterNotOpen +@throw ::ErrorPathUndefined +@throw ::ErrorNoBufferForElement +@throw ::ErrorBufferSizeMismatch +@throw ::ErrorBufferDuplicatePathName +@throw ::ErrorConversionRequired This CompressedVectorWriter in undocumented state, associated +ImageFile modified but consistent. +@throw ::ErrorValueOutOfBounds This CompressedVectorWriter in undocumented state, associated +ImageFile modified but consistent. +@throw ::ErrorValueNotRepresentable This CompressedVectorWriter in undocumented state, associated +ImageFile modified but consistent. +@throw ::ErrorScaledValueNotRepresentable This CompressedVectorWriter in undocumented state, +associated ImageFile modified but consistent. +@throw ::ErrorReal64TooLarge This CompressedVectorWriter in undocumented state, associated ImageFile +modified but consistent. +@throw ::ErrorExpectingNumeric This CompressedVectorWriter in undocumented state, associated +ImageFile modified but consistent. +@throw ::ErrorExpectingUString This CompressedVectorWriter in undocumented state, associated +ImageFile modified but consistent. +@throw ::ErrorSeekFailed This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorReadFailed This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorWriteFailed This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorBadChecksum This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorWriter::write(unsigned), CompressedVectorNode::writer, +CompressedVectorWriter::close, SourceDestBuffer, E57Exception +*/ +void CompressedVectorWriter::write( std::vector &sbufs, const size_t recordCount ) +{ + impl_->write( sbufs, recordCount ); +} + +/*! +@brief End the write operation. + +@details +This function must be called to safely and gracefully end a transfer to a CompressedVectorNode. This +is required because errors cannot be communicated from the CompressedVectorNode destructor (in C++ +destructors can't throw exceptions). It is not an error to call this function if the +CompressedVectorWriter is already closed. This function will cause the CompressedVectorWriter to +enter the closed state, and any further transfers requests will fail. + +@warning If this function is not called before the CompressedVectorWriter destructor is invoked, all +writes to the CompressedVectorNode will be lost (it will have zero children). + +@pre The associated ImageFile must be open. +@post This CompressedVectorWriter is closed (i.e !isOpen()) + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorSeekFailed This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorReadFailed This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorWriteFailed This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorBadChecksum This CompressedVectorWriter, associated ImageFile in undocumented state +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorWriter::isOpen +*/ +void CompressedVectorWriter::close() +{ + impl_->close(); +} + +/*! +@brief Test whether CompressedVectorWriter is still open for writing. + +@pre The associated ImageFile must be open. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorWriter::close, CompressedVectorNode::writer +*/ +bool CompressedVectorWriter::isOpen() +{ + return impl_->isOpen(); +} + +/*! +@brief Return the CompressedVectorNode being written to. + +@pre The associated ImageFile must be open. + +@return A smart CompressedVectorNode handle referencing the underlying object being written to. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorNode::writer +*/ +CompressedVectorNode CompressedVectorWriter::compressedVectorNode() const +{ + return impl_->compressedVectorNode(); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void CompressedVectorWriter::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void CompressedVectorWriter::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif diff --git a/src/3rdParty/libE57Format/src/CompressedVectorWriterImpl.cpp b/src/3rdParty/libE57Format/src/CompressedVectorWriterImpl.cpp index c57da72d63de3..f7efff7f60c30 100644 --- a/src/3rdParty/libE57Format/src/CompressedVectorWriterImpl.cpp +++ b/src/3rdParty/libE57Format/src/CompressedVectorWriterImpl.cpp @@ -34,84 +34,88 @@ #include "ImageFileImpl.h" #include "SectionHeaders.h" #include "SourceDestBufferImpl.h" +#include "StringFunctions.h" namespace e57 { struct SortByBytestreamNumber { - bool operator()( const std::shared_ptr &lhs, const std::shared_ptr &rhs ) const + bool operator()( const std::shared_ptr &lhs, + const std::shared_ptr &rhs ) const { return ( lhs->bytestreamNumber() < rhs->bytestreamNumber() ); } }; - CompressedVectorWriterImpl::CompressedVectorWriterImpl( std::shared_ptr ni, - std::vector &sbufs ) : + CompressedVectorWriterImpl::CompressedVectorWriterImpl( + std::shared_ptr ni, std::vector &sbufs ) : cVector_( ni ), isOpen_( false ) // set to true when succeed below { //??? check if cvector already been written (can't write twice) - /// Empty sbufs is an error + // Empty sbufs is an error if ( sbufs.empty() ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_API_ARGUMENT, - "imageFileName=" + cVector_->imageFileName() + " cvPathName=" + cVector_->pathName() ); + throw E57_EXCEPTION2( ErrorBadAPIArgument, "imageFileName=" + cVector_->imageFileName() + + " cvPathName=" + cVector_->pathName() ); } - /// Get CompressedArray's prototype node (all array elements must match this - /// type) + // Get CompressedArray's prototype node (all array elements must match this + // type) proto_ = cVector_->getPrototype(); - /// Check sbufs well formed (matches proto exactly) + // Check sbufs well formed (matches proto exactly) setBuffers( sbufs ); //??? copy code here? - /// For each individual sbuf, create an appropriate Encoder based on the - /// cVector_ attributes + // For each individual sbuf, create an appropriate Encoder based on the + // cVector_ attributes for ( unsigned i = 0; i < sbufs_.size(); i++ ) { - /// Create vector of single sbuf ??? for now, may have groups later + // Create vector of single sbuf ??? for now, may have groups later std::vector vTemp; vTemp.push_back( sbufs_.at( i ) ); ustring codecPath = sbufs_.at( i ).pathName(); - /// Calc which stream the given path belongs to. This depends on position - /// of the node in the proto tree. + // Calc which stream the given path belongs to. This depends on position + // of the node in the proto tree. NodeImplSharedPtr readNode = proto_->get( sbufs.at( i ).pathName() ); uint64_t bytestreamNumber = 0; if ( !proto_->findTerminalPosition( readNode, bytestreamNumber ) ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "sbufIndex=" + toString( i ) ); + throw E57_EXCEPTION2( ErrorInternal, "sbufIndex=" + toString( i ) ); } - /// EncoderFactory picks the appropriate encoder to match type declared in - /// prototype - bytestreams_.push_back( - Encoder::EncoderFactory( static_cast( bytestreamNumber ), cVector_, vTemp, codecPath ) ); + // EncoderFactory picks the appropriate encoder to match type declared in + // prototype + bytestreams_.push_back( Encoder::EncoderFactory( static_cast( bytestreamNumber ), + cVector_, vTemp, codecPath ) ); } - /// The bytestreams_ vector must be ordered by bytestreamNumber, not by order - /// called specified sbufs, so sort it. + // The bytestreams_ vector must be ordered by bytestreamNumber, not by order + // called specified sbufs, so sort it. sort( bytestreams_.begin(), bytestreams_.end(), SortByBytestreamNumber() ); -#ifdef E57_MAX_DEBUG - /// Double check that all bytestreams are specified +#if ( E57_VALIDATION_LEVEL == VALIDATION_DEEP ) + // Double check that all bytestreams are specified for ( unsigned i = 0; i < bytestreams_.size(); i++ ) { if ( bytestreams_.at( i )->bytestreamNumber() != i ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "bytestreamIndex=" + toString( i ) + " bytestreamNumber=" + - toString( bytestreams_.at( i )->bytestreamNumber() ) ); + throw E57_EXCEPTION2( ErrorInternal, + "bytestreamIndex=" + toString( i ) + " bytestreamNumber=" + + toString( bytestreams_.at( i )->bytestreamNumber() ) ); } } #endif ImageFileImplSharedPtr imf( ni->destImageFile_ ); - /// Reserve space for CompressedVector binary section header, record location - /// so can save to when writer closes. Request that file be extended with - /// zeros since we will write to it at a later time (when writer closes). - sectionHeaderLogicalStart_ = imf->allocateSpace( sizeof( CompressedVectorSectionHeader ), true ); + // Reserve space for CompressedVector binary section header, record location + // so can save to when writer closes. Request that file be extended with + // zeros since we will write to it at a later time (when writer closes). + sectionHeaderLogicalStart_ = + imf->allocateSpace( sizeof( CompressedVectorSectionHeader ), true ); sectionLogicalLength_ = 0; dataPhysicalOffset_ = 0; @@ -120,17 +124,17 @@ namespace e57 dataPacketsCount_ = 0; indexPacketsCount_ = 0; - /// Just before return (and can't throw) increment writer count ??? safer - /// way to assure don't miss close? + // Just before return (and can't throw) increment writer count ??? safer + // way to assure don't miss close? imf->incrWriterCount(); - /// If get here, the writer is open + // If get here, the writer is open isOpen_ = true; } CompressedVectorWriterImpl::~CompressedVectorWriterImpl() { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "~CompressedVectorWriterImpl() called" << std::endl; //??? #endif @@ -149,30 +153,30 @@ namespace e57 void CompressedVectorWriterImpl::close() { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "CompressedVectorWriterImpl::close() called" << std::endl; //??? #endif ImageFileImplSharedPtr imf( cVector_->destImageFile_ ); - /// Before anything that can throw, decrement writer count + // Before anything that can throw, decrement writer count imf->decrWriterCount(); checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - /// don't call checkWriterOpen(); + // don't call checkWriterOpen(); if ( !isOpen_ ) { return; } - /// Set closed before do anything, so if get fault and start unwinding, don't - /// try to close again. + // Set closed before do anything, so if get fault and start unwinding, don't + // try to close again. isOpen_ = false; - /// If have any data, write packet - /// Write all remaining ioBuffers and internal encoder register cache into - /// file. Know we are done when totalOutputAvailable() returns 0 after a - /// flush(). + // If have any data, write packet + // Write all remaining ioBuffers and internal encoder register cache into + // file. Know we are done when totalOutputAvailable() returns 0 after a + // flush(). flush(); while ( totalOutputAvailable() > 0 ) { @@ -180,40 +184,43 @@ namespace e57 flush(); } - /// Compute length of whole section we just wrote (from section start to - /// current start of free space). + // Compute length of whole section we just wrote (from section start to + // current start of free space). sectionLogicalLength_ = imf->unusedLogicalStart_ - sectionHeaderLogicalStart_; -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " sectionLogicalLength_=" << sectionLogicalLength_ << std::endl; //??? #endif - /// Prepare CompressedVectorSectionHeader + // Prepare CompressedVectorSectionHeader CompressedVectorSectionHeader header; header.sectionLogicalLength = sectionLogicalLength_; - header.dataPhysicalOffset = dataPhysicalOffset_; ///??? can be zero, if no data written ???not set yet - header.indexPhysicalOffset = topIndexPhysicalOffset_; ///??? can be zero, if no data written ???not set - /// yet -#ifdef E57_MAX_VERBOSE + header.dataPhysicalOffset = + dataPhysicalOffset_; //??? can be zero, if no data written ???not set yet + header.indexPhysicalOffset = + topIndexPhysicalOffset_; //??? can be zero, if no data written ???not set + // yet +#ifdef E57_VERBOSE std::cout << " CompressedVectorSectionHeader:" << std::endl; header.dump( 4 ); //??? #endif -#ifdef E57_DEBUG - /// Verify OK before write it. + +#if VALIDATE_BASIC + // Verify OK before write it. header.verify( imf->file_->length( CheckedFile::Physical ) ); #endif - /// Write header at beginning of section, previously allocated + // Write header at beginning of section, previously allocated imf->file_->seek( sectionHeaderLogicalStart_ ); imf->file_->write( reinterpret_cast( &header ), sizeof( header ) ); - /// Set address and size of associated CompressedVector + // Set address and size of associated CompressedVector cVector_->setRecordCount( recordCount_ ); cVector_->setBinarySectionLogicalStart( sectionHeaderLogicalStart_ ); - /// Free channels + // Free channels bytestreams_.clear(); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " CompressedVectorWriter:" << std::endl; dump( 4 ); #endif @@ -221,28 +228,30 @@ namespace e57 bool CompressedVectorWriterImpl::isOpen() const { - /// don't checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__), or - /// checkWriterOpen() + // don't checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__), or + // checkWriterOpen() return isOpen_; } - std::shared_ptr CompressedVectorWriterImpl::compressedVectorNode() const + std::shared_ptr CompressedVectorWriterImpl::compressedVectorNode() + const { return cVector_; } void CompressedVectorWriterImpl::setBuffers( std::vector &sbufs ) { - /// don't checkImageFileOpen + // don't checkImageFileOpen - /// If had previous sbufs_, check to see if new ones have changed in - /// incompatible way + // If had previous sbufs_, check to see if new ones have changed in + // incompatible way if ( !sbufs_.empty() ) { if ( sbufs_.size() != sbufs.size() ) { - throw E57_EXCEPTION2( E57_ERROR_BUFFERS_NOT_COMPATIBLE, - "oldSize=" + toString( sbufs_.size() ) + " newSize=" + toString( sbufs.size() ) ); + throw E57_EXCEPTION2( ErrorBuffersNotCompatible, + "oldSize=" + toString( sbufs_.size() ) + + " newSize=" + toString( sbufs.size() ) ); } for ( size_t i = 0; i < sbufs_.size(); ++i ) @@ -250,23 +259,24 @@ namespace e57 std::shared_ptr oldbuf = sbufs_[i].impl(); std::shared_ptr newBuf = sbufs[i].impl(); - /// Throw exception if old and new not compatible + // Throw exception if old and new not compatible oldbuf->checkCompatible( newBuf ); } } - /// Check sbufs well formed: no dups, no missing, no extra - /// For writing, all data fields in prototype must be presented for writing - /// at same time. + // Check sbufs well formed: no dups, no missing, no extra + // For writing, all data fields in prototype must be presented for writing + // at same time. proto_->checkBuffers( sbufs, false ); sbufs_ = sbufs; } - void CompressedVectorWriterImpl::write( std::vector &sbufs, const size_t requestedRecordCount ) + void CompressedVectorWriterImpl::write( std::vector &sbufs, + const size_t requestedRecordCount ) { - /// don't checkImageFileOpen, write(unsigned) will do it - /// don't checkWriterOpen(), write(unsigned) will do it + // don't checkImageFileOpen, write(unsigned) will do it + // don't checkWriterOpen(), write(unsigned) will do it setBuffers( sbufs ); write( requestedRecordCount ); @@ -274,78 +284,79 @@ namespace e57 void CompressedVectorWriterImpl::write( const size_t requestedRecordCount ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "CompressedVectorWriterImpl::write() called" << std::endl; //??? #endif checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); checkWriterOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - /// Check that requestedRecordCount is not larger than the sbufs + // Check that requestedRecordCount is not larger than the sbufs if ( requestedRecordCount > sbufs_.at( 0 ).impl()->capacity() ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_API_ARGUMENT, + throw E57_EXCEPTION2( ErrorBadAPIArgument, "requested=" + toString( requestedRecordCount ) + - " capacity=" + toString( sbufs_.at( 0 ).impl()->capacity() ) + " imageFileName=" + - cVector_->imageFileName() + " cvPathName=" + cVector_->pathName() ); + " capacity=" + toString( sbufs_.at( 0 ).impl()->capacity() ) + + " imageFileName=" + cVector_->imageFileName() + + " cvPathName=" + cVector_->pathName() ); } - /// Rewind all sbufs so start reading from beginning + // Rewind all sbufs so start reading from beginning for ( auto &sbuf : sbufs_ ) { sbuf.impl()->rewind(); } - /// Loop until all channels have completed requestedRecordCount transfers + // Loop until all channels have completed requestedRecordCount transfers uint64_t endRecordIndex = recordCount_ + requestedRecordCount; while ( true ) { - /// Calc remaining record counts for all channels + // Calc remaining record counts for all channels uint64_t totalRecordCount = 0; for ( auto &bytestream : bytestreams_ ) { totalRecordCount += endRecordIndex - bytestream->currentRecordIndex(); } -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " totalRecordCount=" << totalRecordCount << std::endl; //??? #endif - /// We are done if have no more work, break out of loop + // We are done if have no more work, break out of loop if ( totalRecordCount == 0 ) { break; } - /// Estimate how many records can write before have enough data to fill - /// data packet to efficient length Efficient packet length is >= 75% - /// of maximum packet length. It is OK if get too much data (more than - /// one packet) in an iteration. Reader will be able to handle packets - /// whose streams are not exactly synchronized to the record - /// boundaries. But try to do a good job of keeping the stream - /// synchronization "close enough" (so a reader that can cache only two - /// packets is efficient). + // Estimate how many records can write before have enough data to fill + // data packet to efficient length Efficient packet length is >= 75% + // of maximum packet length. It is OK if get too much data (more than + // one packet) in an iteration. Reader will be able to handle packets + // whose streams are not exactly synchronized to the record + // boundaries. But try to do a good job of keeping the stream + // synchronization "close enough" (so a reader that can cache only two + // packets is efficient). -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " currentPacketSize()=" << currentPacketSize() << std::endl; //??? #endif #ifdef E57_WRITE_CRAZY_PACKET_MODE - ///??? depends on number of streams + //??? depends on number of streams constexpr size_t E57_TARGET_PACKET_SIZE = 500; #else constexpr size_t E57_TARGET_PACKET_SIZE = ( DATA_PACKET_MAX * 3 / 4 ); #endif - /// If have more than target fraction of packet, send it now + // If have more than target fraction of packet, send it now if ( currentPacketSize() >= E57_TARGET_PACKET_SIZE ) { //??? packetWrite(); - continue; /// restart loop so recalc statistics (packet size may not be - /// zero after write, if have too much data) + continue; // restart loop so recalc statistics (packet size may not be + // zero after write, if have too much data) } -#ifdef E57_MAX_VERBOSE - ///??? useful? - /// Get approximation of number of bytes per record of CompressedVector - /// and total of bytes used +#ifdef E57_VERBOSE + //??? useful? + // Get approximation of number of bytes per record of CompressedVector + // and total of bytes used float totalBitsPerRecord = 0; // an estimate of future performance for ( auto &bytestream : bytestreams_ ) { @@ -357,19 +368,20 @@ namespace e57 std::cout << " totalBytesPerRecord=" << totalBytesPerRecord << std::endl; //??? #endif - /// Don't allow straggler to get too far behind. ??? - /// Don't allow a single channel to get too far ahead ??? - /// Process channels that are furthest behind first. ??? + // Don't allow straggler to get too far behind. ??? + // Don't allow a single channel to get too far ahead ??? + // Process channels that are furthest behind first. ??? - ///!!!! For now just process one record per loop until packet is full - /// enough, or completed request + // !!!! For now just process one record per loop until packet is full + // enough, or completed request for ( auto &bytestream : bytestreams_ ) { if ( bytestream->currentRecordIndex() < endRecordIndex ) { - //!!! For now, process up to 50 records at a time + // !!! For now, process up to 50 records at a time uint64_t recordCount = endRecordIndex - bytestream->currentRecordIndex(); - recordCount = ( recordCount < 50ULL ) ? recordCount : 50ULL; // min(recordCount, 50ULL); + recordCount = + ( recordCount < 50ULL ) ? recordCount : 50ULL; // min(recordCount, 50ULL); bytestream->processRecords( static_cast( recordCount ) ); } } @@ -377,8 +389,8 @@ namespace e57 recordCount_ += requestedRecordCount; - /// When we leave this function, will likely still have data in channel - /// ioBuffers as well as partial words in Encoder registers. + // When we leave this function, will likely still have data in channel + // ioBuffers as well as partial words in Encoder registers. } size_t CompressedVectorWriterImpl::totalOutputAvailable() const @@ -395,197 +407,206 @@ namespace e57 size_t CompressedVectorWriterImpl::currentPacketSize() const { - /// Calc current packet size - return ( sizeof( DataPacketHeader ) + bytestreams_.size() * sizeof( uint16_t ) + totalOutputAvailable() ); + // Calc current packet size + return ( sizeof( DataPacketHeader ) + bytestreams_.size() * sizeof( uint16_t ) + + totalOutputAvailable() ); } uint64_t CompressedVectorWriterImpl::packetWrite() { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "CompressedVectorWriterImpl::packetWrite() called" << std::endl; //??? #endif - /// Double check that we have work to do - size_t totalOutput = totalOutputAvailable(); - if ( totalOutput == 0 ) + // Double check that we have work to do + const size_t cTotalOutput = totalOutputAvailable(); + if ( cTotalOutput == 0 ) { return ( 0 ); } -#ifdef E57_MAX_VERBOSE - std::cout << " totalOutput=" << totalOutput << std::endl; //??? -#endif - /// Calc maximum number of bytestream values can put in data packet. - size_t packetMaxPayloadBytes = - DATA_PACKET_MAX - sizeof( DataPacketHeader ) - bytestreams_.size() * sizeof( uint16_t ); -#ifdef E57_MAX_VERBOSE - std::cout << " packetMaxPayloadBytes=" << packetMaxPayloadBytes << std::endl; //??? + // const bytestreams_ so it's clear it isn't modified in this function + const auto &cStreams = bytestreams_; + const auto cNumByteStreams = cStreams.size(); + + // Calc maximum number of bytestream values can put in data packet. + const size_t cPacketMaxPayloadBytes = + DATA_PACKET_MAX - sizeof( DataPacketHeader ) - cNumByteStreams * sizeof( uint16_t ); + +#ifdef E57_VERBOSE + std::cout << " totalOutput=" << cTotalOutput << std::endl; + std::cout << " cNumByteStreams=" << cNumByteStreams << std::endl; + std::cout << " packetMaxPayloadBytes=" << cPacketMaxPayloadBytes << std::endl; #endif - /// Allocate vector for number of bytes that each bytestream will write to - /// file. - std::vector count( bytestreams_.size() ); + // Allocate vector for number of bytes that each bytestream will write to file. + std::vector count( cNumByteStreams ); - /// See if we can fit into a single data packet - if ( totalOutput < packetMaxPayloadBytes ) + // See if we can fit into a single data packet + if ( cTotalOutput < cPacketMaxPayloadBytes ) { - /// We can fit everything in one packet - for ( unsigned i = 0; i < bytestreams_.size(); i++ ) + // We can fit everything in one packet + for ( unsigned i = 0; i < cNumByteStreams; ++i ) { - count.at( i ) = bytestreams_.at( i )->outputAvailable(); + count.at( i ) = cStreams.at( i )->outputAvailable(); } } else { - /// We have too much data for one packet. Send proportional amounts from - /// each bytestream. Adjust packetMaxPayloadBytes down by one so have a - /// little slack for floating point weirdness. - float fractionToSend = ( packetMaxPayloadBytes - 1 ) / static_cast( totalOutput ); - for ( unsigned i = 0; i < bytestreams_.size(); i++ ) + // We have too much data for one packet. Send proportional amounts from + // each bytestream. Adjust packetMaxPayloadBytes down by one so have a + // little slack for floating point weirdness. + const float cFractionToSend = + ( cPacketMaxPayloadBytes - 1 ) / static_cast( cTotalOutput ); + for ( unsigned i = 0; i < cNumByteStreams; ++i ) { - /// Round down here so sum <= packetMaxPayloadBytes - count.at( i ) = - static_cast( std::floor( fractionToSend * bytestreams_.at( i )->outputAvailable() ) ); + // Round down here so sum <= packetMaxPayloadBytes + count.at( i ) = static_cast( + std::floor( cFractionToSend * cStreams.at( i )->outputAvailable() ) ); } } -#ifdef E57_MAX_VERBOSE - for ( unsigned i = 0; i < bytestreams_.size(); i++ ) + +#ifdef E57_VERBOSE + for ( unsigned i = 0; i < cNumByteStreams; ++i ) { - std::cout << " count[" << i << "]=" << count.at( i ) << std::endl; //??? + std::cout << " count[" << i << "]=" << count.at( i ) << std::endl; } #endif -#ifdef E57_DEBUG - /// Double check sum of count is <= packetMaxPayloadBytes - const size_t totalByteCount = std::accumulate( count.begin(), count.end(), 0 ); +#if VALIDATE_BASIC + // Double check sum of count is <= packetMaxPayloadBytes + const size_t cTotalByteCount = + std::accumulate( count.begin(), count.end(), static_cast( 0 ) ); - if ( totalByteCount > packetMaxPayloadBytes ) + if ( cTotalByteCount > cPacketMaxPayloadBytes ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "totalByteCount=" + toString( totalByteCount ) + - " packetMaxPayloadBytes=" + toString( packetMaxPayloadBytes ) ); + throw E57_EXCEPTION2( ErrorInternal, + "totalByteCount=" + toString( cTotalByteCount ) + + " packetMaxPayloadBytes=" + toString( cPacketMaxPayloadBytes ) ); } #endif - /// Get smart pointer to ImageFileImpl from associated CompressedVector + // Get smart pointer to ImageFileImpl from associated CompressedVector ImageFileImplSharedPtr imf( cVector_->destImageFile_ ); - /// Use temp buf in object (is 64KBytes long) instead of allocating each time - /// here + // Use temp buf in object (is 64KBytes long) instead of allocating each time here char *packet = reinterpret_cast( &dataPacket_ ); -#ifdef E57_MAX_VERBOSE - std::cout << " packet=" << packet << std::endl; //??? -#endif - /// To be safe, clear header part of packet + // To be safe, clear header part of packet dataPacket_.header.reset(); - /// Write bytestreamBufferLength[bytestreamCount] after header, in - /// dataPacket_ + // Write bytestreamBufferLength[bytestreamCount] after header, in dataPacket_ auto bsbLength = reinterpret_cast( &packet[sizeof( DataPacketHeader )] ); -#ifdef E57_MAX_VERBOSE - std::cout << " bsbLength=" << bsbLength << std::endl; //??? +#ifdef E57_VERBOSE + std::cout << " packet=" << static_cast( packet ) << std::endl; //??? + std::cout << " bsbLength=" << bsbLength << std::endl; //??? #endif - for ( unsigned i = 0; i < bytestreams_.size(); i++ ) + for ( unsigned i = 0; i < cNumByteStreams; ++i ) { bsbLength[i] = static_cast( count.at( i ) ); // %%% Truncation -#ifdef E57_MAX_VERBOSE - std::cout << " Writing " << bsbLength[i] << " bytes into bytestream " << i << std::endl; //??? +#ifdef E57_VERBOSE + std::cout << " Writing " << bsbLength[i] << " bytes into bytestream " << i + << std::endl; //??? #endif } - /// Get pointer to end of data so far - char *p = reinterpret_cast( &bsbLength[bytestreams_.size()] ); -#ifdef E57_MAX_VERBOSE - std::cout << " after bsbLength, p=" << p << std::endl; //??? + // Get pointer to end of data so far + auto *p = reinterpret_cast( &bsbLength[cNumByteStreams] ); +#ifdef E57_VERBOSE + std::cout << " after bsbLength, p=" << static_cast( p ) << std::endl; //??? #endif - /// Write contents of each bytestream in dataPacket_ - for ( size_t i = 0; i < bytestreams_.size(); i++ ) + // Write contents of each bytestream in dataPacket_ + for ( size_t i = 0; i < cNumByteStreams; ++i ) { size_t n = count.at( i ); -#ifdef E57_DEBUG - /// Double check we aren't accidentally going to write off end of - /// vector +#if VALIDATE_BASIC + // Double check we aren't accidentally going to write off end of vector if ( &p[n] > &packet[DATA_PACKET_MAX] ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "n=" + toString( n ) ); + throw E57_EXCEPTION2( ErrorInternal, "n=" + toString( n ) ); } #endif - /// Read from encoder output into packet - bytestreams_.at( i )->outputRead( p, n ); + // Read from encoder output into packet + cStreams.at( i )->outputRead( p, n ); - /// Move pointer to end of current data + // Move pointer to end of current data p += n; } - /// Length of packet is difference in beginning pointer and ending pointer - auto packetLength = static_cast( p - packet ); ///??? pointer diff portable? -#ifdef E57_MAX_VERBOSE + // Length of packet is difference in beginning pointer and ending pointer + auto packetLength = static_cast( p - packet ); //??? pointer diff portable? +#ifdef E57_VERBOSE std::cout << " packetLength=" << packetLength << std::endl; //??? #endif -#ifdef E57_DEBUG - /// Double check that packetLength is what we expect - if ( packetLength != sizeof( DataPacketHeader ) + bytestreams_.size() * sizeof( uint16_t ) + totalByteCount ) +#if VALIDATE_BASIC + // Double check that packetLength is what we expect + if ( packetLength != + sizeof( DataPacketHeader ) + cNumByteStreams * sizeof( uint16_t ) + cTotalByteCount ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "packetLength=" + toString( packetLength ) + " bytestreamSize=" + - toString( bytestreams_.size() * sizeof( uint16_t ) ) + - " totalByteCount=" + toString( totalByteCount ) ); + throw E57_EXCEPTION2( ErrorInternal, "packetLength=" + toString( packetLength ) + + " bytestreamSize=" + + toString( cNumByteStreams * sizeof( uint16_t ) ) + + " totalByteCount=" + toString( cTotalByteCount ) ); } #endif - /// packetLength must be multiple of 4, if not, add some zero padding + // packetLength must be multiple of 4, if not, add some zero padding while ( packetLength % 4 ) { - /// Double check we aren't accidentally going to write off end of - /// vector + // Double check we aren't accidentally going to write off end of + // vector if ( p >= &packet[DATA_PACKET_MAX - 1] ) { - throw E57_EXCEPTION1( E57_ERROR_INTERNAL ); + throw E57_EXCEPTION1( ErrorInternal ); } *p++ = 0; packetLength++; -#ifdef E57_MAX_VERBOSE - std::cout << " padding with zero byte, new packetLength=" << packetLength << std::endl; //??? +#ifdef E57_VERBOSE + std::cout << " padding with zero byte, new packetLength=" << packetLength + << std::endl; //??? #endif } - /// Prepare header in dataPacket_, now that we are sure of packetLength - dataPacket_.header.packetLogicalLengthMinus1 = static_cast( packetLength - 1 ); // %%% Truncation - dataPacket_.header.bytestreamCount = static_cast( bytestreams_.size() ); // %%% Truncation + // Prepare header in dataPacket_, now that we are sure of packetLength + dataPacket_.header.packetLogicalLengthMinus1 = + static_cast( packetLength - 1 ); // %%% Truncation + dataPacket_.header.bytestreamCount = + static_cast( cNumByteStreams ); // %%% Truncation - /// Double check that data packet is well formed + // Double check that data packet is well formed dataPacket_.verify( packetLength ); - /// Write whole data packet at beginning of free space in file + // Write whole data packet at beginning of free space in file uint64_t packetLogicalOffset = imf->allocateSpace( packetLength, false ); uint64_t packetPhysicalOffset = imf->file_->logicalToPhysical( packetLogicalOffset ); imf->file_->seek( packetLogicalOffset ); //??? have seekLogical and seekPhysical instead? // more explicit imf->file_->write( packet, packetLength ); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE // std::cout << "data packet:" << std::endl; // dataPacket_.dump(4); #endif - /// If first data packet written for this CompressedVector binary section, - /// save address to put in section header - ///??? what if no data packets? - ///??? what if have exceptions while write, what is state of file? will - /// close report file - /// good/bad? + // If first data packet written for this CompressedVector binary section, + // save address to put in section header + //??? what if no data packets? + //??? what if have exceptions while write, what is state of file? will + // close report file + // good/bad? if ( dataPacketsCount_ == 0 ) { dataPhysicalOffset_ = packetPhysicalOffset; } dataPacketsCount_++; - ///!!! update seekIndex here? if started new chunk? + // !!! update seekIndex here? if started new chunk? - /// Return physical offset of data packet for potential use in seekIndex + // Return physical offset of data packet for potential use in seekIndex return ( packetPhysicalOffset ); //??? needed } @@ -601,7 +622,9 @@ namespace e57 const char *srcFunctionName ) const { // unimplemented... - (void)srcFileName; (void)srcLineNumber; (void)srcFunctionName; + UNUSED( srcFileName ); + UNUSED( srcLineNumber ); + UNUSED( srcFunctionName ); } void CompressedVectorWriterImpl::checkWriterOpen( const char *srcFileName, int srcLineNumber, @@ -609,13 +632,14 @@ namespace e57 { if ( !isOpen_ ) { - throw E57Exception( E57_ERROR_WRITER_NOT_OPEN, - "imageFileName=" + cVector_->imageFileName() + " cvPathName=" + cVector_->pathName(), + throw E57Exception( ErrorWriterNotOpen, + "imageFileName=" + cVector_->imageFileName() + + " cvPathName=" + cVector_->pathName(), srcFileName, srcLineNumber, srcFunctionName ); } } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void CompressedVectorWriterImpl::dump( int indent, std::ostream &os ) { os << space( indent ) << "isOpen:" << isOpen_ << std::endl; @@ -638,21 +662,24 @@ namespace e57 bytestreams_.at( i )->dump( indent + 4, os ); } - /// Don't call dump() for DataPacket, since it may contain junk when - /// debugging. Just print a few byte values. + // Don't call dump() for DataPacket, since it may contain junk when + // debugging. Just print a few byte values. os << space( indent ) << "dataPacket:" << std::endl; auto p = reinterpret_cast( &dataPacket_ ); for ( unsigned i = 0; i < 40; ++i ) { - os << space( indent + 4 ) << "dataPacket[" << i << "]: " << static_cast( p[i] ) << std::endl; + os << space( indent + 4 ) << "dataPacket[" << i << "]: " << static_cast( p[i] ) + << std::endl; } os << space( indent + 4 ) << "more unprinted..." << std::endl; - os << space( indent ) << "sectionHeaderLogicalStart: " << sectionHeaderLogicalStart_ << std::endl; + os << space( indent ) << "sectionHeaderLogicalStart: " << sectionHeaderLogicalStart_ + << std::endl; os << space( indent ) << "sectionLogicalLength: " << sectionLogicalLength_ << std::endl; os << space( indent ) << "dataPhysicalOffset: " << dataPhysicalOffset_ << std::endl; - os << space( indent ) << "topIndexPhysicalOffset: " << topIndexPhysicalOffset_ << std::endl; + os << space( indent ) << "topIndexPhysicalOffset: " << topIndexPhysicalOffset_ + << std::endl; os << space( indent ) << "recordCount: " << recordCount_ << std::endl; os << space( indent ) << "dataPacketsCount: " << dataPacketsCount_ << std::endl; os << space( indent ) << "indexPacketsCount: " << indexPacketsCount_ << std::endl; diff --git a/src/3rdParty/libE57Format/src/CompressedVectorWriterImpl.h b/src/3rdParty/libE57Format/src/CompressedVectorWriterImpl.h index 3b1808ab17420..80f6d68f114fd 100644 --- a/src/3rdParty/libE57Format/src/CompressedVectorWriterImpl.h +++ b/src/3rdParty/libE57Format/src/CompressedVectorWriterImpl.h @@ -34,29 +34,31 @@ namespace e57 class CompressedVectorWriterImpl { public: - CompressedVectorWriterImpl( std::shared_ptr ni, std::vector &sbufs ); + CompressedVectorWriterImpl( std::shared_ptr ni, + std::vector &sbufs ); ~CompressedVectorWriterImpl(); - void write( const size_t requestedRecordCount ); - void write( std::vector &sbufs, const size_t requestedRecordCount ); + + void write( size_t requestedRecordCount ); + void write( std::vector &sbufs, size_t requestedRecordCount ); bool isOpen() const; std::shared_ptr compressedVectorNode() const; void close(); -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ); #endif private: - void checkImageFileOpen( const char *srcFileName, int srcLineNumber, const char *srcFunctionName ) const; - void checkWriterOpen( const char *srcFileName, int srcLineNumber, const char *srcFunctionName ) const; + void checkImageFileOpen( const char *srcFileName, int srcLineNumber, + const char *srcFunctionName ) const; + void checkWriterOpen( const char *srcFileName, int srcLineNumber, + const char *srcFunctionName ) const; void setBuffers( std::vector &sbufs ); //???needed? size_t totalOutputAvailable() const; size_t currentPacketSize() const; uint64_t packetWrite(); void flush(); - //??? no default ctor, copy, assignment? - std::vector sbufs_; std::shared_ptr cVector_; NodeImplSharedPtr proto_; diff --git a/src/3rdParty/libE57Format/src/DecodeChannel.cpp b/src/3rdParty/libE57Format/src/DecodeChannel.cpp index 043a7e60ba471..e1f9a965b3f78 100644 --- a/src/3rdParty/libE57Format/src/DecodeChannel.cpp +++ b/src/3rdParty/libE57Format/src/DecodeChannel.cpp @@ -27,6 +27,7 @@ #include "DecodeChannel.h" #include "SourceDestBufferImpl.h" +#include "StringFunctions.h" namespace e57 { @@ -44,30 +45,30 @@ namespace e57 bool DecodeChannel::isOutputBlocked() const { - /// If we have completed the entire vector, we are done + // If we have completed the entire vector, we are done if ( decoder->totalRecordsCompleted() >= maxRecordCount ) { return ( true ); } - /// If we have filled the dest buffer, we are blocked + // If we have filled the dest buffer, we are blocked return ( dbuf.impl()->nextIndex() == dbuf.impl()->capacity() ); } bool DecodeChannel::isInputBlocked() const { - /// If have read until the section end, we are done + // If have read until the section end, we are done if ( inputFinished ) { return ( true ); } - /// If have eaten all the input in the current packet, we are blocked. + // If have eaten all the input in the current packet, we are blocked. return ( currentBytestreamBufferIndex == currentBytestreamBufferLength ); } -#ifdef E57_DEBUG - void DecodeChannel::dump( int indent, std::ostream &os ) +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT + void DecodeChannel::dump( int indent, std::ostream &os ) const { os << space( indent ) << "dbuf" << std::endl; dbuf.dump( indent + 4, os ); @@ -77,9 +78,12 @@ namespace e57 os << space( indent ) << "bytestreamNumber: " << bytestreamNumber << std::endl; os << space( indent ) << "maxRecordCount: " << maxRecordCount << std::endl; - os << space( indent ) << "currentPacketLogicalOffset: " << currentPacketLogicalOffset << std::endl; - os << space( indent ) << "currentBytestreamBufferIndex: " << currentBytestreamBufferIndex << std::endl; - os << space( indent ) << "currentBytestreamBufferLength: " << currentBytestreamBufferLength << std::endl; + os << space( indent ) << "currentPacketLogicalOffset: " << currentPacketLogicalOffset + << std::endl; + os << space( indent ) << "currentBytestreamBufferIndex: " << currentBytestreamBufferIndex + << std::endl; + os << space( indent ) << "currentBytestreamBufferLength: " << currentBytestreamBufferLength + << std::endl; os << space( indent ) << "inputFinished: " << inputFinished << std::endl; os << space( indent ) << "isInputBlocked(): " << isInputBlocked() << std::endl; os << space( indent ) << "isOutputBlocked(): " << isOutputBlocked() << std::endl; diff --git a/src/3rdParty/libE57Format/src/DecodeChannel.h b/src/3rdParty/libE57Format/src/DecodeChannel.h index c458f0d3a76ca..7de90f15761c9 100644 --- a/src/3rdParty/libE57Format/src/DecodeChannel.h +++ b/src/3rdParty/libE57Format/src/DecodeChannel.h @@ -34,7 +34,7 @@ namespace e57 struct DecodeChannel { - SourceDestBuffer dbuf; //??? for now, one input per channel + SourceDestBuffer dbuf; std::shared_ptr decoder; unsigned bytestreamNumber; uint64_t maxRecordCount; @@ -43,13 +43,14 @@ namespace e57 size_t currentBytestreamBufferLength; bool inputFinished; - DecodeChannel( SourceDestBuffer dbuf_arg, std::shared_ptr decoder_arg, unsigned bytestreamNumber_arg, - uint64_t maxRecordCount_arg ); + DecodeChannel( SourceDestBuffer dbuf_arg, std::shared_ptr decoder_arg, + unsigned bytestreamNumber_arg, uint64_t maxRecordCount_arg ); bool isOutputBlocked() const; bool isInputBlocked() const; /// has exhausted data in the current packet -#ifdef E57_DEBUG - void dump( int indent = 0, std::ostream &os = std::cout ); + +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT + void dump( int indent = 0, std::ostream &os = std::cout ) const; #endif }; } diff --git a/src/3rdParty/libE57Format/src/Decoder.cpp b/src/3rdParty/libE57Format/src/Decoder.cpp index 8b4f468a12abe..ed00ae8da9384 100644 --- a/src/3rdParty/libE57Format/src/Decoder.cpp +++ b/src/3rdParty/libE57Format/src/Decoder.cpp @@ -35,21 +35,23 @@ #include "IntegerNodeImpl.h" #include "ScaledIntegerNodeImpl.h" #include "SourceDestBufferImpl.h" +#include "StringFunctions.h" using namespace e57; std::shared_ptr Decoder::DecoderFactory( unsigned bytestreamNumber, //!!! name ok? const CompressedVectorNodeImpl *cVector, - std::vector &dbufs, const ustring & /*codecPath*/ ) + std::vector &dbufs, + const ustring & /*codecPath*/ ) { - //!!! verify single dbuf + // !!! verify single dbuf - /// Get node we are going to decode from the CompressedVector's prototype + // Get node we are going to decode from the CompressedVector's prototype NodeImplSharedPtr prototype = cVector->getPrototype(); ustring path = dbufs.at( 0 ).pathName(); NodeImplSharedPtr decodeNode = prototype->get( path ); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "Node to decode:" << std::endl; //??? decodeNode->dump( 2 ); #endif @@ -58,118 +60,125 @@ std::shared_ptr Decoder::DecoderFactory( unsigned bytestreamNumber, //! switch ( decodeNode->type() ) { - case E57_INTEGER: + case TypeInteger: { std::shared_ptr ini = std::static_pointer_cast( decodeNode ); // downcast to correct type - /// Get pointer to parent ImageFileImpl, to call bitsNeeded() - ImageFileImplSharedPtr imf( decodeNode->destImageFile_ ); //??? should be function for this, - // imf->parentFile() - //--> ImageFile? + // Get pointer to parent ImageFileImpl, to call bitsNeeded() + ImageFileImplSharedPtr imf( + decodeNode->destImageFile_ ); //??? should be function for this, + // imf->parentFile() + //--> ImageFile? unsigned bitsPerRecord = imf->bitsNeeded( ini->minimum(), ini->maximum() ); - //!!! need to pick smarter channel buffer sizes, here and elsewhere - /// Constuct Integer decoder with appropriate register size, based on - /// number of bits stored. + // !!! need to pick smarter channel buffer sizes, here and elsewhere + // Construct Integer decoder with appropriate register size, based on + // number of bits stored. if ( bitsPerRecord == 0 ) { - std::shared_ptr decoder( new ConstantIntegerDecoder( false, bytestreamNumber, dbufs.at( 0 ), - ini->minimum(), 1.0, 0.0, maxRecordCount ) ); + std::shared_ptr decoder( new ConstantIntegerDecoder( + false, bytestreamNumber, dbufs.at( 0 ), ini->minimum(), 1.0, 0.0, maxRecordCount ) ); return decoder; } if ( bitsPerRecord <= 8 ) { std::shared_ptr decoder( new BitpackIntegerDecoder( - false, bytestreamNumber, dbufs.at( 0 ), ini->minimum(), ini->maximum(), 1.0, 0.0, maxRecordCount ) ); + false, bytestreamNumber, dbufs.at( 0 ), ini->minimum(), ini->maximum(), 1.0, 0.0, + maxRecordCount ) ); return decoder; } if ( bitsPerRecord <= 16 ) { std::shared_ptr decoder( new BitpackIntegerDecoder( - false, bytestreamNumber, dbufs.at( 0 ), ini->minimum(), ini->maximum(), 1.0, 0.0, maxRecordCount ) ); + false, bytestreamNumber, dbufs.at( 0 ), ini->minimum(), ini->maximum(), 1.0, 0.0, + maxRecordCount ) ); return decoder; } if ( bitsPerRecord <= 32 ) { std::shared_ptr decoder( new BitpackIntegerDecoder( - false, bytestreamNumber, dbufs.at( 0 ), ini->minimum(), ini->maximum(), 1.0, 0.0, maxRecordCount ) ); + false, bytestreamNumber, dbufs.at( 0 ), ini->minimum(), ini->maximum(), 1.0, 0.0, + maxRecordCount ) ); return decoder; } std::shared_ptr decoder( new BitpackIntegerDecoder( - false, bytestreamNumber, dbufs.at( 0 ), ini->minimum(), ini->maximum(), 1.0, 0.0, maxRecordCount ) ); + false, bytestreamNumber, dbufs.at( 0 ), ini->minimum(), ini->maximum(), 1.0, 0.0, + maxRecordCount ) ); return decoder; } - case E57_SCALED_INTEGER: + case TypeScaledInteger: { std::shared_ptr sini = - std::static_pointer_cast( decodeNode ); // downcast to correct type + std::static_pointer_cast( + decodeNode ); // downcast to correct type - /// Get pointer to parent ImageFileImpl, to call bitsNeeded() - ImageFileImplSharedPtr imf( decodeNode->destImageFile_ ); //??? should be function for this, - // imf->parentFile() - //--> ImageFile? + // Get pointer to parent ImageFileImpl, to call bitsNeeded() + ImageFileImplSharedPtr imf( + decodeNode->destImageFile_ ); //??? should be function for this, + // imf->parentFile() + //--> ImageFile? unsigned bitsPerRecord = imf->bitsNeeded( sini->minimum(), sini->maximum() ); - //!!! need to pick smarter channel buffer sizes, here and elsewhere - /// Construct ScaledInteger dencoder with appropriate register size, - /// based on number of bits stored. + // !!! need to pick smarter channel buffer sizes, here and elsewhere + // Construct ScaledInteger decoder with appropriate register size, + // based on number of bits stored. if ( bitsPerRecord == 0 ) { - std::shared_ptr decoder( new ConstantIntegerDecoder( true, bytestreamNumber, dbufs.at( 0 ), - sini->minimum(), sini->scale(), - sini->offset(), maxRecordCount ) ); + std::shared_ptr decoder( + new ConstantIntegerDecoder( true, bytestreamNumber, dbufs.at( 0 ), sini->minimum(), + sini->scale(), sini->offset(), maxRecordCount ) ); return decoder; } if ( bitsPerRecord <= 8 ) { - std::shared_ptr decoder( - new BitpackIntegerDecoder( true, bytestreamNumber, dbufs.at( 0 ), sini->minimum(), - sini->maximum(), sini->scale(), sini->offset(), maxRecordCount ) ); + std::shared_ptr decoder( new BitpackIntegerDecoder( + true, bytestreamNumber, dbufs.at( 0 ), sini->minimum(), sini->maximum(), + sini->scale(), sini->offset(), maxRecordCount ) ); return decoder; } if ( bitsPerRecord <= 16 ) { - std::shared_ptr decoder( - new BitpackIntegerDecoder( true, bytestreamNumber, dbufs.at( 0 ), sini->minimum(), - sini->maximum(), sini->scale(), sini->offset(), maxRecordCount ) ); + std::shared_ptr decoder( new BitpackIntegerDecoder( + true, bytestreamNumber, dbufs.at( 0 ), sini->minimum(), sini->maximum(), + sini->scale(), sini->offset(), maxRecordCount ) ); return decoder; } if ( bitsPerRecord <= 32 ) { - std::shared_ptr decoder( - new BitpackIntegerDecoder( true, bytestreamNumber, dbufs.at( 0 ), sini->minimum(), - sini->maximum(), sini->scale(), sini->offset(), maxRecordCount ) ); + std::shared_ptr decoder( new BitpackIntegerDecoder( + true, bytestreamNumber, dbufs.at( 0 ), sini->minimum(), sini->maximum(), + sini->scale(), sini->offset(), maxRecordCount ) ); return decoder; } - std::shared_ptr decoder( - new BitpackIntegerDecoder( true, bytestreamNumber, dbufs.at( 0 ), sini->minimum(), - sini->maximum(), sini->scale(), sini->offset(), maxRecordCount ) ); + std::shared_ptr decoder( new BitpackIntegerDecoder( + true, bytestreamNumber, dbufs.at( 0 ), sini->minimum(), sini->maximum(), sini->scale(), + sini->offset(), maxRecordCount ) ); return decoder; } - case E57_FLOAT: + case TypeFloat: { std::shared_ptr fni = std::static_pointer_cast( decodeNode ); // downcast to correct type - std::shared_ptr decoder( - new BitpackFloatDecoder( bytestreamNumber, dbufs.at( 0 ), fni->precision(), maxRecordCount ) ); + std::shared_ptr decoder( new BitpackFloatDecoder( + bytestreamNumber, dbufs.at( 0 ), fni->precision(), maxRecordCount ) ); return decoder; } - case E57_STRING: + case TypeString: { std::shared_ptr decoder( new BitpackStringDecoder( bytestreamNumber, dbufs.at( 0 ), maxRecordCount ) ); @@ -179,7 +188,7 @@ std::shared_ptr Decoder::DecoderFactory( unsigned bytestreamNumber, //! default: { - throw E57_EXCEPTION2( E57_ERROR_BAD_PROTOTYPE, "nodeType=" + toString( decodeNode->type() ) ); + throw E57_EXCEPTION2( ErrorBadPrototype, "nodeType=" + toString( decodeNode->type() ) ); } } } @@ -188,12 +197,13 @@ Decoder::Decoder( unsigned bytestreamNumber ) : bytestreamNumber_( bytestreamNum { } -BitpackDecoder::BitpackDecoder( unsigned bytestreamNumber, SourceDestBuffer &dbuf, unsigned alignmentSize, - uint64_t maxRecordCount ) : +BitpackDecoder::BitpackDecoder( unsigned bytestreamNumber, SourceDestBuffer &dbuf, + unsigned alignmentSize, uint64_t maxRecordCount ) : Decoder( bytestreamNumber ), maxRecordCount_( maxRecordCount ), destBuffer_( dbuf.impl() ), - inBuffer_( 1024 ), //!!! need to pick smarter channel buffer sizes - inBufferAlignmentSize_( alignmentSize ), bitsPerWord_( 8 * alignmentSize ), bytesPerWord_( alignmentSize ) + inBuffer_( 1024 ), // !!! need to pick smarter channel buffer sizes + inBufferAlignmentSize_( alignmentSize ), bitsPerWord_( 8 * alignmentSize ), + bytesPerWord_( alignmentSize ) { } @@ -201,7 +211,7 @@ void BitpackDecoder::destBufferSetNew( std::vector &dbufs ) { if ( dbufs.size() != 1 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "dbufsSize=" + toString( dbufs.size() ) ); + throw E57_EXCEPTION2( ErrorInternal, "dbufsSize=" + toString( dbufs.size() ) ); } destBuffer_ = dbufs.at( 0 ).impl(); @@ -209,7 +219,7 @@ void BitpackDecoder::destBufferSetNew( std::vector &dbufs ) size_t BitpackDecoder::inputProcess( const char *source, const size_t availableByteCount ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "BitpackDecoder::inputprocess() called, source=" << ( source ? source : "none" ) << " availableByteCount=" << availableByteCount << std::endl; #endif @@ -217,28 +227,29 @@ size_t BitpackDecoder::inputProcess( const char *source, const size_t availableB size_t bitsEaten = 0; do { - size_t byteCount = std::min( bytesUnsaved, inBuffer_.size() - static_cast( inBufferEndByte_ ) ); + size_t byteCount = + std::min( bytesUnsaved, inBuffer_.size() - static_cast( inBufferEndByte_ ) ); - /// Copy input bytes from caller, if any - if ( ( byteCount > 0 ) && source ) + // Copy input bytes from caller, if any + if ( ( byteCount > 0 ) && ( source != nullptr ) ) { memcpy( &inBuffer_[inBufferEndByte_], source, byteCount ); - /// Advance tail pointer. + // Advance tail pointer. inBufferEndByte_ += byteCount; - /// Update amount available from caller + // Update amount available from caller bytesUnsaved -= byteCount; source += byteCount; } -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE { unsigned i; unsigned firstByte = inBufferFirstBit_ / 8; for ( i = 0; i < byteCount && i < 20; i++ ) { - std::cout << " inBuffer[" << firstByte + i << "]=" << (unsigned)(unsigned char)( inBuffer_[firstByte + i] ) - << std::endl; + std::cout << " inBuffer[" << firstByte + i + << "]=" << (unsigned)(unsigned char)( inBuffer_[firstByte + i] ) << std::endl; } if ( i < byteCount ) { @@ -247,45 +258,48 @@ size_t BitpackDecoder::inputProcess( const char *source, const size_t availableB } #endif - /// ??? fix doc for new bit interface - /// Now that we have input stored in an aligned buffer, call derived class - /// to try to eat some Note that end of filled buffer may not be at a - /// natural boundary. The subclass may transfer this partial word in a - /// full word transfer, but it must be done carefully to only use the defined - /// bits. inBuffer_ is a multiple of largest word size, so this full word - /// transfer off the end will always be in defined memory. + // ??? fix doc for new bit interface + // Now that we have input stored in an aligned buffer, call derived class + // to try to eat some Note that end of filled buffer may not be at a + // natural boundary. The subclass may transfer this partial word in a + // full word transfer, but it must be careful to only use the defined + // bits. inBuffer_ is a multiple of largest word size, so this full word + // transfer off the end will always be in defined memory. size_t firstWord = inBufferFirstBit_ / bitsPerWord_; size_t firstNaturalBit = firstWord * bitsPerWord_; size_t endBit = inBufferEndByte_ * 8; -#ifdef E57_MAX_VERBOSE - std::cout << " feeding aligned decoder " << endBit - inBufferFirstBit_ << " bits." << std::endl; +#ifdef E57_VERBOSE + std::cout << " feeding aligned decoder " << endBit - inBufferFirstBit_ << " bits." + << std::endl; #endif - bitsEaten = inputProcessAligned( &inBuffer_[firstWord * bytesPerWord_], inBufferFirstBit_ - firstNaturalBit, - endBit - firstNaturalBit ); -#ifdef E57_MAX_VERBOSE - std::cout << " bitsEaten=" << bitsEaten << " firstWord=" << firstWord << " firstNaturalBit=" << firstNaturalBit - << " endBit=" << endBit << std::endl; + bitsEaten = + inputProcessAligned( &inBuffer_[firstWord * bytesPerWord_], + inBufferFirstBit_ - firstNaturalBit, endBit - firstNaturalBit ); +#ifdef E57_VERBOSE + std::cout << " bitsEaten=" << bitsEaten << " firstWord=" << firstWord + << " firstNaturalBit=" << firstNaturalBit << " endBit=" << endBit << std::endl; #endif -#ifdef E57_DEBUG + +#if VALIDATE_BASIC if ( bitsEaten > endBit - inBufferFirstBit_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "bitsEaten=" + toString( bitsEaten ) + - " endBit=" + toString( endBit ) + - " inBufferFirstBit=" + toString( inBufferFirstBit_ ) ); + throw E57_EXCEPTION2( + ErrorInternal, "bitsEaten=" + toString( bitsEaten ) + " endBit=" + toString( endBit ) + + " inBufferFirstBit=" + toString( inBufferFirstBit_ ) ); } #endif inBufferFirstBit_ += bitsEaten; - /// Shift uneaten data to beginning of inBuffer_, keep on natural word - /// boundaries. + // Shift uneaten data to beginning of inBuffer_, keep on natural word + // boundaries. inBufferShiftDown(); - /// If the lower level processing didn't eat anything on this iteration, - /// stop looping and tell caller how much we ate or stored. + // If the lower level processing didn't eat anything on this iteration, + // stop looping and tell caller how much we ate or stored. } while ( bytesUnsaved > 0 && bitsEaten > 0 ); - /// Return the number of bytes we ate/saved. + // Return the number of bytes we ate/saved. return ( availableByteCount - bytesUnsaved ); } @@ -297,31 +311,32 @@ void BitpackDecoder::stateReset() void BitpackDecoder::inBufferShiftDown() { - /// Move uneaten data down to beginning of inBuffer_. - /// Keep on natural boundaries. - /// Moves all of word that contains inBufferFirstBit. + // Move uneaten data down to beginning of inBuffer_. + // Keep on natural boundaries. + // Moves all of word that contains inBufferFirstBit. size_t firstWord = inBufferFirstBit_ / bitsPerWord_; size_t firstNaturalByte = firstWord * bytesPerWord_; -#ifdef E57_DEBUG + +#if VALIDATE_BASIC if ( firstNaturalByte > inBufferEndByte_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "firstNaturalByte=" + toString( firstNaturalByte ) + - " inBufferEndByte=" + toString( inBufferEndByte_ ) ); + throw E57_EXCEPTION2( ErrorInternal, "firstNaturalByte=" + toString( firstNaturalByte ) + + " inBufferEndByte=" + toString( inBufferEndByte_ ) ); } #endif size_t byteCount = inBufferEndByte_ - firstNaturalByte; if ( byteCount > 0 ) { - memmove( &inBuffer_[0], &inBuffer_[firstNaturalByte], - byteCount ); /// Overlapping regions ok with memmove(). + memmove( inBuffer_.data(), &inBuffer_[firstNaturalByte], + byteCount ); // Overlapping regions ok with memmove(). } - /// Update indexes + // Update indexes inBufferEndByte_ = byteCount; inBufferFirstBit_ = inBufferFirstBit_ % bitsPerWord_; } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void BitpackDecoder::dump( int indent, std::ostream &os ) { os << space( indent ) << "bytestreamNumber: " << bytestreamNumber_ << std::endl; @@ -339,7 +354,8 @@ void BitpackDecoder::dump( int indent, std::ostream &os ) for ( i = 0; i < inBuffer_.size() && i < 20; i++ ) { os << space( indent + 4 ) << "inBuffer[" << i - << "]: " << static_cast( static_cast( inBuffer_.at( i ) ) ) << std::endl; + << "]: " << static_cast( static_cast( inBuffer_.at( i ) ) ) + << std::endl; } if ( i < inBuffer_.size() ) { @@ -350,48 +366,51 @@ void BitpackDecoder::dump( int indent, std::ostream &os ) //================================================================ -BitpackFloatDecoder::BitpackFloatDecoder( unsigned bytestreamNumber, SourceDestBuffer &dbuf, FloatPrecision precision, - uint64_t maxRecordCount ) : - BitpackDecoder( bytestreamNumber, dbuf, ( precision == E57_SINGLE ) ? sizeof( float ) : sizeof( double ), +BitpackFloatDecoder::BitpackFloatDecoder( unsigned bytestreamNumber, SourceDestBuffer &dbuf, + FloatPrecision precision, uint64_t maxRecordCount ) : + BitpackDecoder( bytestreamNumber, dbuf, + ( precision == PrecisionSingle ) ? sizeof( float ) : sizeof( double ), maxRecordCount ), precision_( precision ) { } -size_t BitpackFloatDecoder::inputProcessAligned( const char *inbuf, const size_t firstBit, const size_t endBit ) +size_t BitpackFloatDecoder::inputProcessAligned( const char *inbuf, const size_t firstBit, + const size_t endBit ) { -#ifdef E57_MAX_VERBOSE - std::cout << "BitpackFloatDecoder::inputProcessAligned() called, inbuf=" << inbuf << " firstBit=" << firstBit +#ifdef E57_VERBOSE + std::cout << "BitpackFloatDecoder::inputProcessAligned() called, inbuf=" + << reinterpret_cast( inbuf ) << " firstBit=" << firstBit << " endBit=" << endBit << std::endl; #endif - /// Read from inbuf, decode, store in destBuffer - /// Repeat until have filled destBuffer, or completed all records + // Read from inbuf, decode, store in destBuffer + // Repeat until have filled destBuffer, or completed all records size_t n = destBuffer_->capacity() - destBuffer_->nextIndex(); - size_t typeSize = ( precision_ == E57_SINGLE ) ? sizeof( float ) : sizeof( double ); + size_t typeSize = ( precision_ == PrecisionSingle ) ? sizeof( float ) : sizeof( double ); -#ifdef E57_DEBUG +#if VALIDATE_BASIC #if 0 // I know no way to do this portably // Deactivate for now until a better solution is found. - /// Verify that inbuf is naturally aligned to correct boundary (4 or 8 bytes). Base class should be doing this for us. + // Verify that inbuf is naturally aligned to correct boundary (4 or 8 bytes). Base class should be doing this for us. if (reinterpret_cast(inbuf) % typeSize) { - throw E57_EXCEPTION2(E57_ERROR_INTERNAL, + throw E57_EXCEPTION2(ErrorInternal, "inbuf=" + toString(reinterpret_cast(inbuf)) + " typeSize=" + toString(typeSize)); } #endif - /// Verify first bit is zero + // Verify first bit is zero if ( firstBit != 0 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "firstBit=" + toString( firstBit ) ); + throw E57_EXCEPTION2( ErrorInternal, "firstBit=" + toString( firstBit ) ); } #endif - /// Calc how many whole records worth of data we have in inbuf + // Calc how many whole records worth of data we have in inbuf size_t maxInputRecords = ( endBit - firstBit ) / ( 8 * typeSize ); - /// Can't process more records than we have input data for. + // Can't process more records than we have input data for. if ( n > maxInputRecords ) { n = maxInputRecords; @@ -403,21 +422,21 @@ size_t BitpackFloatDecoder::inputProcessAligned( const char *inbuf, const size_t n = static_cast( maxRecordCount_ - currentRecordIndex_ ); } -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " n:" << n << std::endl; //??? #endif - if ( precision_ == E57_SINGLE ) + if ( precision_ == PrecisionSingle ) { - /// Form the starting address for first data location in inBuffer + // Form the starting address for first data location in inBuffer auto inp = reinterpret_cast( inbuf ); - /// Copy floats from inbuf to destBuffer_ + // Copy floats from inbuf to destBuffer_ for ( unsigned i = 0; i < n; i++ ) { float value = *inp; -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " got float value=" << value << std::endl; #endif destBuffer_->setNextFloat( value ); @@ -425,16 +444,16 @@ size_t BitpackFloatDecoder::inputProcessAligned( const char *inbuf, const size_t } } else - { /// E57_DOUBLE precision - /// Form the starting address for first data location in inBuffer + { // Double precision + // Form the starting address for first data location in inBuffer auto inp = reinterpret_cast( inbuf ); - /// Copy doubles from inbuf to destBuffer_ + // Copy doubles from inbuf to destBuffer_ for ( unsigned i = 0; i < n; i++ ) { double value = *inp; -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " got double value=" << value << std::endl; #endif destBuffer_->setNextDouble( value ); @@ -442,24 +461,24 @@ size_t BitpackFloatDecoder::inputProcessAligned( const char *inbuf, const size_t } } - /// Update counts of records processed + // Update counts of records processed currentRecordIndex_ += n; - /// Returned number of bits processed (always a multiple of alignment size). + // Returned number of bits processed (always a multiple of alignment size). return ( n * 8 * typeSize ); } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void BitpackFloatDecoder::dump( int indent, std::ostream &os ) { BitpackDecoder::dump( indent, os ); - if ( precision_ == E57_SINGLE ) + if ( precision_ == PrecisionSingle ) { - os << space( indent ) << "precision: E57_SINGLE" << std::endl; + os << space( indent ) << "precision: Single" << std::endl; } else { - os << space( indent ) << "precision: E57_DOUBLE" << std::endl; + os << space( indent ) << "precision: Double" << std::endl; } } #endif @@ -472,42 +491,45 @@ BitpackStringDecoder::BitpackStringDecoder( unsigned bytestreamNumber, SourceDes { } -size_t BitpackStringDecoder::inputProcessAligned( const char *inbuf, const size_t firstBit, const size_t endBit ) +size_t BitpackStringDecoder::inputProcessAligned( const char *inbuf, const size_t firstBit, + const size_t endBit ) { -#ifdef E57_MAX_VERBOSE - std::cout << "BitpackStringDecoder::inputProcessAligned() called, inbuf=" << inbuf << " firstBit=" << firstBit - << " endBit=" << endBit << std::endl; +#ifdef E57_VERBOSE + std::cout << "BitpackStringDecoder::inputProcessAligned() called, inbuf=" << inbuf + << " firstBit=" << firstBit << " endBit=" << endBit << std::endl; #endif - /// Read from inbuf, decode, store in destBuffer - /// Repeat until have filled destBuffer, or completed all records + // Read from inbuf, decode, store in destBuffer + // Repeat until have filled destBuffer, or completed all records -#ifdef E57_DEBUG - /// Verify first bit is zero (always byte-aligned) +#if VALIDATE_BASIC + // Verify first bit is zero (always byte-aligned) if ( firstBit != 0 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "firstBit=" + toString( firstBit ) ); + throw E57_EXCEPTION2( ErrorInternal, "firstBit=" + toString( firstBit ) ); } #endif - /// Converts start/end bits to whole bytes + // Converts start/end bits to whole bytes size_t nBytesAvailable = ( endBit - firstBit ) >> 3; size_t nBytesRead = 0; - /// Loop until we've finished all the records, or ran out of input currently - /// available + // Loop until we've finished all the records, or ran out of input currently + // available while ( currentRecordIndex_ < maxRecordCount_ && nBytesRead < nBytesAvailable ) { -#ifdef E57_MAX_VERBOSE - std::cout << "read string loop1: readingPrefix=" << readingPrefix_ << " prefixLength=" << prefixLength_ - << " nBytesPrefixRead=" << nBytesPrefixRead_ << " nBytesStringRead=" << nBytesStringRead_ << std::endl; +#ifdef E57_VERBOSE + std::cout << "read string loop1: readingPrefix=" << readingPrefix_ + << " prefixLength=" << prefixLength_ << " nBytesPrefixRead=" << nBytesPrefixRead_ + << " nBytesStringRead=" << nBytesStringRead_ << std::endl; #endif if ( readingPrefix_ ) { - /// Try to read more prefix bytes - while ( nBytesRead < nBytesAvailable && ( nBytesPrefixRead_ == 0 || nBytesPrefixRead_ < prefixLength_ ) ) + // Try to read more prefix bytes + while ( nBytesRead < nBytesAvailable && + ( nBytesPrefixRead_ == 0 || nBytesPrefixRead_ < prefixLength_ ) ) { - /// If first byte of prefix, test the least significant bit to see - /// how long prefix is + // If first byte of prefix, test the least significant bit to see + // how long prefix is if ( nBytesPrefixRead_ == 0 ) { if ( *inbuf & 0x01 ) @@ -520,33 +542,33 @@ size_t BitpackStringDecoder::inputProcessAligned( const char *inbuf, const size_ } } - /// Accumulate prefix bytes + // Accumulate prefix bytes prefixBytes_[nBytesPrefixRead_] = *inbuf++; nBytesPrefixRead_++; nBytesRead++; } -#ifdef E57_MAX_VERBOSE - std::cout << "read string loop2: readingPrefix=" << readingPrefix_ << " prefixLength=" << prefixLength_ - << " nBytesPrefixRead=" << nBytesPrefixRead_ << " nBytesStringRead=" << nBytesStringRead_ - << std::endl; +#ifdef E57_VERBOSE + std::cout << "read string loop2: readingPrefix=" << readingPrefix_ + << " prefixLength=" << prefixLength_ << " nBytesPrefixRead=" << nBytesPrefixRead_ + << " nBytesStringRead=" << nBytesStringRead_ << std::endl; #endif - /// If got all of prefix, convert to length and get ready to read - /// string + // If got all of prefix, convert to length and get ready to read + // string if ( nBytesPrefixRead_ > 0 && nBytesPrefixRead_ == prefixLength_ ) { if ( prefixLength_ == 1 ) { - /// Single byte prefix, extract length from b7-b1. - /// Removing the least significant bit (which says this is a - /// short prefix). + // Single byte prefix, extract length from b7-b1. + // Removing the least significant bit (which says this is a + // short prefix). stringLength_ = static_cast( prefixBytes_[0] >> 1 ); } else { - /// Eight byte prefix, extract length from b63-b1. Little endian - /// ordering. Removing the least significant bit (which says this - /// is a long prefix). + // Eight byte prefix, extract length from b63-b1. Little endian + // ordering. Removing the least significant bit (which says this + // is a long prefix). stringLength_ = ( static_cast( prefixBytes_[0] ) >> 1 ) + ( static_cast( prefixBytes_[1] ) << ( 1 * 8 - 1 ) ) + ( static_cast( prefixBytes_[2] ) << ( 2 * 8 - 1 ) ) + @@ -556,7 +578,7 @@ size_t BitpackStringDecoder::inputProcessAligned( const char *inbuf, const size_ ( static_cast( prefixBytes_[6] ) << ( 6 * 8 - 1 ) ) + ( static_cast( prefixBytes_[7] ) << ( 7 * 8 - 1 ) ); } - /// Get ready to read string contents + // Get ready to read string contents readingPrefix_ = false; prefixLength_ = 1; memset( prefixBytes_, 0, sizeof( prefixBytes_ ) ); @@ -564,41 +586,41 @@ size_t BitpackStringDecoder::inputProcessAligned( const char *inbuf, const size_ currentString_ = ""; nBytesStringRead_ = 0; } -#ifdef E57_MAX_VERBOSE - std::cout << "read string loop3: readingPrefix=" << readingPrefix_ << " prefixLength=" << prefixLength_ - << " nBytesPrefixRead=" << nBytesPrefixRead_ << " nBytesStringRead=" << nBytesStringRead_ - << std::endl; +#ifdef E57_VERBOSE + std::cout << "read string loop3: readingPrefix=" << readingPrefix_ + << " prefixLength=" << prefixLength_ << " nBytesPrefixRead=" << nBytesPrefixRead_ + << " nBytesStringRead=" << nBytesStringRead_ << std::endl; #endif } - /// If currently reading string contents, keep doing it until have - /// complete string + // If currently reading string contents, keep doing it until have + // complete string if ( !readingPrefix_ ) { - /// Calc how many bytes we need to complete current string + // Calc how many bytes we need to complete current string uint64_t nBytesNeeded = stringLength_ - nBytesStringRead_; - /// Can process the smaller of unread or needed bytes + // Can process the smaller of unread or needed bytes size_t nBytesProcess = nBytesAvailable - nBytesRead; if ( nBytesNeeded < static_cast( nBytesProcess ) ) { nBytesProcess = static_cast( nBytesNeeded ); } - /// Append to current string and update counts + // Append to current string and update counts currentString_ += ustring( inbuf, nBytesProcess ); inbuf += nBytesProcess; nBytesRead += nBytesProcess; nBytesStringRead_ += nBytesProcess; - /// Check if completed reading the string contents + // Check if completed reading the string contents if ( nBytesStringRead_ == stringLength_ ) { - /// Save accumulated string to dest buffer + // Save accumulated string to dest buffer destBuffer_->setNextString( currentString_ ); currentRecordIndex_++; - /// Get ready to read next prefix + // Get ready to read next prefix readingPrefix_ = true; prefixLength_ = 1; memset( prefixBytes_, 0, sizeof( prefixBytes_ ) ); @@ -610,21 +632,22 @@ size_t BitpackStringDecoder::inputProcessAligned( const char *inbuf, const size_ } } - /// Returned number of bits processed (always a multiple of alignment size). + // Returned number of bits processed (always a multiple of alignment size). return ( nBytesRead * 8 ); } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void BitpackStringDecoder::dump( int indent, std::ostream &os ) { BitpackDecoder::dump( indent, os ); os << space( indent ) << "readingPrefix: " << readingPrefix_ << std::endl; os << space( indent ) << "prefixLength: " << prefixLength_ << std::endl; - os << space( indent ) << "prefixBytes[8]: " << static_cast( prefixBytes_[0] ) << " " - << static_cast( prefixBytes_[1] ) << " " << static_cast( prefixBytes_[2] ) << " " - << static_cast( prefixBytes_[3] ) << " " << static_cast( prefixBytes_[4] ) << " " - << static_cast( prefixBytes_[5] ) << " " << static_cast( prefixBytes_[6] ) << " " - << static_cast( prefixBytes_[7] ) << std::endl; + os << space( indent ) << "prefixBytes[8]: " << static_cast( prefixBytes_[0] ) + << " " << static_cast( prefixBytes_[1] ) << " " + << static_cast( prefixBytes_[2] ) << " " << static_cast( prefixBytes_[3] ) + << " " << static_cast( prefixBytes_[4] ) << " " + << static_cast( prefixBytes_[5] ) << " " << static_cast( prefixBytes_[6] ) + << " " << static_cast( prefixBytes_[7] ) << std::endl; os << space( indent ) << "nBytesPrefixRead: " << nBytesPrefixRead_ << std::endl; os << space( indent ) << "stringLength: " << stringLength_ << std::endl; os << space( indent ) @@ -641,56 +664,61 @@ void BitpackStringDecoder::dump( int indent, std::ostream &os ) //================================================================ template -BitpackIntegerDecoder::BitpackIntegerDecoder( bool isScaledInteger, unsigned bytestreamNumber, - SourceDestBuffer &dbuf, int64_t minimum, int64_t maximum, - double scale, double offset, uint64_t maxRecordCount ) : +BitpackIntegerDecoder::BitpackIntegerDecoder( bool isScaledInteger, + unsigned bytestreamNumber, + SourceDestBuffer &dbuf, int64_t minimum, + int64_t maximum, double scale, + double offset, uint64_t maxRecordCount ) : BitpackDecoder( bytestreamNumber, dbuf, sizeof( RegisterT ), maxRecordCount ), - isScaledInteger_( isScaledInteger ), minimum_( minimum ), maximum_( maximum ), scale_( scale ), offset_( offset ) + isScaledInteger_( isScaledInteger ), minimum_( minimum ), maximum_( maximum ), scale_( scale ), + offset_( offset ) { - /// Get pointer to parent ImageFileImpl + // Get pointer to parent ImageFileImpl ImageFileImplSharedPtr imf( dbuf.impl()->destImageFile() ); //??? should be function for this, // imf->parentFile() --> ImageFile? bitsPerRecord_ = imf->bitsNeeded( minimum_, maximum_ ); - destBitMask_ = ( bitsPerRecord_ == 64 ) ? ~0 : static_cast( 1ULL << bitsPerRecord_ ) - 1; + destBitMask_ = + ( bitsPerRecord_ == 64 ) ? ~0 : static_cast( 1ULL << bitsPerRecord_ ) - 1; } template -size_t BitpackIntegerDecoder::inputProcessAligned( const char *inbuf, const size_t firstBit, +size_t BitpackIntegerDecoder::inputProcessAligned( const char *inbuf, + const size_t firstBit, const size_t endBit ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "BitpackIntegerDecoder::inputProcessAligned() called, inbuf=" << (void *)( inbuf ) << " firstBit=" << firstBit << " endBit=" << endBit << std::endl; #endif - /// Read from inbuf, decode, store in destBuffer - /// Repeat until have filled destBuffer, or completed all records + // Read from inbuf, decode, store in destBuffer + // Repeat until have filled destBuffer, or completed all records -#ifdef E57_DEBUG +#if VALIDATE_BASIC #if 0 // I know now way to do this portably // Deactivate for now until a better solution is found. - /// Verify that inbuf is naturally aligned to RegisterT boundary (1, 2, 4,or 8 bytes). Base class is doing this for us. + // Verify that inbuf is naturally aligned to RegisterT boundary (1, 2, 4,or 8 bytes). Base class is doing this for us. if ((reinterpret_cast(inbuf)) % sizeof(RegisterT)) - throw E57_EXCEPTION2(E57_ERROR_INTERNAL, "inbuf=" + toString(reinterpret_cast(inbuf))); + throw E57_EXCEPTION2(ErrorInternal, "inbuf=" + toString(reinterpret_cast(inbuf))); #endif - /// Verfiy first bit is in first word + // Verify first bit is in first word if ( firstBit >= 8 * sizeof( RegisterT ) ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "firstBit=" + toString( firstBit ) ); + throw E57_EXCEPTION2( ErrorInternal, "firstBit=" + toString( firstBit ) ); } #endif size_t destRecords = destBuffer_->capacity() - destBuffer_->nextIndex(); - /// Precalculate exact number of full records that are in inbuf - /// We can handle the case where don't have a full word at end of inbuf, but - /// all the bits of the record are there; + // Precalculate exact number of full records that are in inbuf + // We can handle the case where don't have a full word at end of inbuf, but + // all the bits of the record are there; size_t bitCount = endBit - firstBit; size_t maxInputRecords = bitCount / bitsPerRecord_; - /// Number of transfers is the smaller of what was requested and what is - /// available in input. + // Number of transfers is the smaller of what was requested and what is + // available in input. size_t recordCount = std::min( destRecords, maxInputRecords ); // Can't process more than defined in input file @@ -699,75 +727,81 @@ size_t BitpackIntegerDecoder::inputProcessAligned( const char *inbuf, recordCount = static_cast( maxRecordCount_ - currentRecordIndex_ ); } -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " recordCount=" << recordCount << std::endl; #endif auto inp = reinterpret_cast( inbuf ); - unsigned wordPosition = 0; /// The index in inbuf of the word we are currently working on. - - /// For example on little endian machine: - /// Assume: registerT=uint32_t, bitOffset=20, destBitMask=0x00007fff (for a - /// 15 bit value). inp[wordPosition] LLLLLLLL LLLLXXXX - /// XXXXXXXX XXXXXXXX Note LSB of value is at bit20 inp(wordPosition+1] - /// XXXXXXXX XXXXXXXX XXXXXXXX XXXXXHHH H=high bits of value, - /// X=uninteresting bits low = inp[i] >> bitOffset 00000000 - /// 00000000 0000LLLL LLLLLLLL L=low bits of value, X=uninteresting bits - /// high = inp[i+1] << (32-bitOffset) XXXXXXXX XXXXXXXX XHHH0000 00000000 - /// w = high | low XXXXXXXX XXXXXXXX XHHHLLLL LLLLLLLL destBitmask 00000000 - /// 00000000 01111111 11111111 w & mask 00000000 - /// 00000000 0HHHLLLL LLLLLLLL + unsigned wordPosition = 0; // The index in inbuf of the word we are currently working on. + + // clang-format off + // For example on little endian machine: + // Assume: registerT=uint32_t, bitOffset=20, destBitMask=0x00007fff (for a 15 bit value). + // inp[wordPosition] LLLLLLLL LLLLXXXX XXXXXXXX XXXXXXXX Note LSB of value is at bit20 + // inp(wordPosition+1] XXXXXXXX XXXXXXXX XXXXXXXX XXXXXHHH H=high bits of value, X=uninteresting bits + // low = inp[i] >> bitOffset 00000000 00000000 0000LLLL LLLLLLLL L=low bits of value, X=uninteresting bits + // high = inp[i+1] << (32-bitOffset) XXXXXXXX XXXXXXXX XHHH0000 00000000 + // w = high | low XXXXXXXX XXXXXXXX XHHHLLLL LLLLLLLL + // destBitmask 00000000 00000000 01111111 11111111 + // w & mask 00000000 00000000 0HHHLLLL LLLLLLLL + // clang-format on size_t bitOffset = firstBit; for ( size_t i = 0; i < recordCount; i++ ) { - /// Get lower word (contains at least the LSbit of the value), + // Get lower word (contains at least the LSbit of the value), RegisterT low = inp[wordPosition]; -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " bitOffset: " << bitOffset << std::endl; std::cout << " low: " << binaryString( low ) << std::endl; #endif RegisterT w; - if ( bitOffset > 0 ) + if ( bitOffset == 0 ) { - /// Get upper word (may or may not contain interesting bits), + // The left shift (used below) is not defined if shift is >= size of + // word + w = low; + } + // Avoid reading the next word, unless it is needed + // If the last record finishes on the last bit of input, avoid UMR + else if ( bitOffset + bitsPerRecord_ <= RegisterBits ) + { + w = low >> bitOffset; + } + else + { + // Get upper word (may or may not contain interesting bits), RegisterT high = inp[wordPosition + 1]; -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " high:" << binaryString( high ) << std::endl; #endif - /// Shift high to just above the lower bits, shift low LSBit to bit0, - /// OR together. Note shifts are logical (not arithmetic) because using - /// unsigned variables. - w = ( high << ( 8 * sizeof( RegisterT ) - bitOffset ) ) | ( low >> bitOffset ); - } - else - { - /// The left shift (used above) is not defined if shift is >= size of - /// word - w = low; + // Shift high to just above the lower bits, shift low LSBit to bit0, + // OR together. Note shifts are logical (not arithmetic) because using + // unsigned variables. + w = ( high << ( RegisterBits - bitOffset ) ) | ( low >> bitOffset ); } -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " w: " << binaryString( w ) << std::endl; #endif - /// Mask off uninteresting bits + // Mask off uninteresting bits w &= destBitMask_; - /// Add minimum_ to value to get back what writer originally sent + // Add minimum_ to value to get back what writer originally sent int64_t value = minimum_ + static_cast( w ); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " Storing value=" << value << std::endl; #endif - /// The parameter isScaledInteger_ determines which version of - /// setNextInt64 gets called + // The parameter isScaledInteger_ determines which version of + // setNextInt64 gets called if ( isScaledInteger_ ) { destBuffer_->setNextInt64( value, scale_, offset_ ); @@ -777,30 +811,32 @@ size_t BitpackIntegerDecoder::inputProcessAligned( const char *inbuf, destBuffer_->setNextInt64( value ); } - /// Store the result in next avaiable position in the user's dest buffer + // Store the result in next available position in the user's dest buffer - /// Calc next bit alignment and which word it starts in + // Calc next bit alignment and which word it starts in bitOffset += bitsPerRecord_; if ( bitOffset >= 8 * sizeof( RegisterT ) ) { bitOffset -= 8 * sizeof( RegisterT ); wordPosition++; } -#ifdef E57_MAX_VERBOSE - std::cout << " Processed " << i + 1 << " records, wordPosition=" << wordPosition << " decoder:" << std::endl; +#ifdef E57_VERBOSE + std::cout << " Processed " << i + 1 << " records, wordPosition=" << wordPosition + << " decoder:" << std::endl; dump( 4 ); #endif } - /// Update counts of records processed + // Update counts of records processed currentRecordIndex_ += recordCount; - /// Return number of bits processed. + // Return number of bits processed. return ( recordCount * bitsPerRecord_ ); } -#ifdef E57_DEBUG -template void BitpackIntegerDecoder::dump( int indent, std::ostream &os ) +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +template +void BitpackIntegerDecoder::dump( int indent, std::ostream &os ) { BitpackDecoder::dump( indent, os ); os << space( indent ) << "isScaledInteger: " << isScaledInteger_ << std::endl; @@ -809,19 +845,20 @@ template void BitpackIntegerDecoder::dump( int i os << space( indent ) << "scale: " << scale_ << std::endl; os << space( indent ) << "offset: " << offset_ << std::endl; os << space( indent ) << "bitsPerRecord: " << bitsPerRecord_ << std::endl; - os << space( indent ) << "destBitMask: " << binaryString( destBitMask_ ) << " = " << hexString( destBitMask_ ) - << std::endl; + os << space( indent ) << "destBitMask: " << binaryString( destBitMask_ ) << " = " + << hexString( destBitMask_ ) << std::endl; } #endif //================================================================ -ConstantIntegerDecoder::ConstantIntegerDecoder( bool isScaledInteger, unsigned bytestreamNumber, SourceDestBuffer &dbuf, - int64_t minimum, double scale, double offset, +ConstantIntegerDecoder::ConstantIntegerDecoder( bool isScaledInteger, unsigned bytestreamNumber, + SourceDestBuffer &dbuf, int64_t minimum, + double scale, double offset, uint64_t maxRecordCount ) : Decoder( bytestreamNumber ), - maxRecordCount_( maxRecordCount ), destBuffer_( dbuf.impl() ), isScaledInteger_( isScaledInteger ), - minimum_( minimum ), scale_( scale ), offset_( offset ) + maxRecordCount_( maxRecordCount ), destBuffer_( dbuf.impl() ), + isScaledInteger_( isScaledInteger ), minimum_( minimum ), scale_( scale ), offset_( offset ) { } @@ -829,7 +866,7 @@ void ConstantIntegerDecoder::destBufferSetNew( std::vector &db { if ( dbufs.size() != 1 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "dbufsSize=" + toString( dbufs.size() ) ); + throw E57_EXCEPTION2( ErrorInternal, "dbufsSize=" + toString( dbufs.size() ) ); } destBuffer_ = dbufs.at( 0 ).impl(); @@ -837,16 +874,18 @@ void ConstantIntegerDecoder::destBufferSetNew( std::vector &db size_t ConstantIntegerDecoder::inputProcess( const char *source, const size_t availableByteCount ) { - (void)source; (void)availableByteCount; -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "ConstantIntegerDecoder::inputprocess() called, source=" << (void *)( source ) << " availableByteCount=" << availableByteCount << std::endl; +#else + UNUSED( source ); + UNUSED( availableByteCount ); #endif - /// We don't need any input bytes to produce output, so ignore source and - /// availableByteCount. + // We don't need any input bytes to produce output, so ignore source and + // availableByteCount. - /// Fill dest buffer unless get to maxRecordCount + // Fill dest buffer unless get to maxRecordCount size_t count = destBuffer_->capacity() - destBuffer_->nextIndex(); uint64_t remainingRecordCount = maxRecordCount_ - currentRecordIndex_; if ( static_cast( count ) > remainingRecordCount ) @@ -876,7 +915,7 @@ void ConstantIntegerDecoder::stateReset() { } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void ConstantIntegerDecoder::dump( int indent, std::ostream &os ) { os << space( indent ) << "bytestreamNumber: " << bytestreamNumber_ << std::endl; diff --git a/src/3rdParty/libE57Format/src/Decoder.h b/src/3rdParty/libE57Format/src/Decoder.h index 7d9496c5c4a35..bc4089f9612f4 100644 --- a/src/3rdParty/libE57Format/src/Decoder.h +++ b/src/3rdParty/libE57Format/src/Decoder.h @@ -36,24 +36,27 @@ namespace e57 public: static std::shared_ptr DecoderFactory( unsigned bytestreamNumber, const CompressedVectorNodeImpl *cVector, - std::vector &dbufs, const ustring &codecPath ); + std::vector &dbufs, + const ustring &codecPath ); Decoder() = delete; virtual ~Decoder() = default; virtual void destBufferSetNew( std::vector &dbufs ) = 0; virtual uint64_t totalRecordsCompleted() = 0; - virtual size_t inputProcess( const char *source, const size_t count ) = 0; + virtual size_t inputProcess( const char *source, size_t count ) = 0; virtual void stateReset() = 0; + unsigned bytestreamNumber() const { return bytestreamNumber_; } -#ifdef E57_DEBUG + +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT virtual void dump( int indent = 0, std::ostream &os = std::cout ) = 0; #endif protected: - Decoder( unsigned bytestreamNumber ); + explicit Decoder( unsigned bytestreamNumber ); unsigned int bytestreamNumber_; }; @@ -68,14 +71,15 @@ namespace e57 return ( currentRecordIndex_ ); } - size_t inputProcess( const char *source, const size_t availableByteCount ) override; - virtual size_t inputProcessAligned( const char *inbuf, const size_t firstBit, const size_t endBit ) = 0; + size_t inputProcess( const char *source, size_t availableByteCount ) override; + virtual size_t inputProcessAligned( const char *inbuf, size_t firstBit, size_t endBit ) = 0; void stateReset() override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) override; #endif + protected: BitpackDecoder( unsigned bytestreamNumber, SourceDestBuffer &dbuf, unsigned alignmentSize, uint64_t maxRecordCount ); @@ -98,28 +102,31 @@ namespace e57 class BitpackFloatDecoder : public BitpackDecoder { public: - BitpackFloatDecoder( unsigned bytestreamNumber, SourceDestBuffer &dbuf, FloatPrecision precision, - uint64_t maxRecordCount ); + BitpackFloatDecoder( unsigned bytestreamNumber, SourceDestBuffer &dbuf, + FloatPrecision precision, uint64_t maxRecordCount ); - size_t inputProcessAligned( const char *inbuf, const size_t firstBit, const size_t endBit ) override; + size_t inputProcessAligned( const char *inbuf, size_t firstBit, size_t endBit ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) override; #endif + protected: - FloatPrecision precision_ = E57_SINGLE; + FloatPrecision precision_ = PrecisionSingle; }; class BitpackStringDecoder : public BitpackDecoder { public: - BitpackStringDecoder( unsigned bytestreamNumber, SourceDestBuffer &dbuf, uint64_t maxRecordCount ); + BitpackStringDecoder( unsigned bytestreamNumber, SourceDestBuffer &dbuf, + uint64_t maxRecordCount ); - size_t inputProcessAligned( const char *inbuf, const size_t firstBit, const size_t endBit ) override; + size_t inputProcessAligned( const char *inbuf, size_t firstBit, size_t endBit ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) override; #endif + protected: bool readingPrefix_ = true; int prefixLength_ = 1; @@ -133,14 +140,16 @@ namespace e57 template class BitpackIntegerDecoder : public BitpackDecoder { public: - BitpackIntegerDecoder( bool isScaledInteger, unsigned bytestreamNumber, SourceDestBuffer &dbuf, int64_t minimum, - int64_t maximum, double scale, double offset, uint64_t maxRecordCount ); + BitpackIntegerDecoder( bool isScaledInteger, unsigned bytestreamNumber, + SourceDestBuffer &dbuf, int64_t minimum, int64_t maximum, double scale, + double offset, uint64_t maxRecordCount ); - size_t inputProcessAligned( const char *inbuf, const size_t firstBit, const size_t endBit ) override; + size_t inputProcessAligned( const char *inbuf, size_t firstBit, size_t endBit ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) override; #endif + protected: bool isScaledInteger_; int64_t minimum_; @@ -149,23 +158,29 @@ namespace e57 double offset_; unsigned bitsPerRecord_; RegisterT destBitMask_; + static constexpr size_t RegisterBits = sizeof( RegisterT ) * 8; }; class ConstantIntegerDecoder : public Decoder { public: - ConstantIntegerDecoder( bool isScaledInteger, unsigned bytestreamNumber, SourceDestBuffer &dbuf, int64_t minimum, - double scale, double offset, uint64_t maxRecordCount ); + ConstantIntegerDecoder( bool isScaledInteger, unsigned bytestreamNumber, + SourceDestBuffer &dbuf, int64_t minimum, double scale, double offset, + uint64_t maxRecordCount ); void destBufferSetNew( std::vector &dbufs ) override; + uint64_t totalRecordsCompleted() override { return currentRecordIndex_; } - size_t inputProcess( const char *source, const size_t availableByteCount ) override; + + size_t inputProcess( const char *source, size_t availableByteCount ) override; void stateReset() override; -#ifdef E57_DEBUG + +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) override; #endif + protected: uint64_t currentRecordIndex_ = 0; uint64_t maxRecordCount_; diff --git a/src/3rdParty/libE57Format/src/E57Exception.cpp b/src/3rdParty/libE57Format/src/E57Exception.cpp index e95afe7724970..137dcbb7eebb1 100644 --- a/src/3rdParty/libE57Format/src/E57Exception.cpp +++ b/src/3rdParty/libE57Format/src/E57Exception.cpp @@ -26,422 +26,341 @@ */ #include "E57Exception.h" -#include "E57Version.h" namespace e57 { /*! @class E57Exception - @brief Object thrown by E57 API functions to communicate the conditions of an - error. + + @brief Object thrown by E57 API functions to communicate the conditions of an error. + @details - The E57Exception object communicates information about errors occurring in calls - to the E57 API functions. The error information is communicated from the - location in the E57 implementation where the error was detected to the @c catch - statement in the code of the API user. The state of E57Exception object has one - mandatory field, the errorCode, and several optional fields that can be set - depending on the debug level of the E57 implementation. There are three optional - fields that encode the location in the source code of the E57 implementation - where the error was detected: @c sourceFileName, @c sourceFunctionName, and @c - sourceLineNumber. Another optional field is the @c context string that is human - (or at least programmer) readable, which can capture some variable values that - might be useful in debugging. The E57Exception class is derived from - std::exception. So applications that only catch std::exceptions will detect - E57Exceptions (but with no information about the origin of the error). - - Many other APIs use error codes (defined integer constants) returned from the - API functions to communicate success or failure of the requested command. In - contrast, the E57 API uses the C++ exception mechanism to communicate failure - (success is communicated by the return of the function without exception). - E57Exception(E57_SUCCESS) is never thrown. The API ErrorCode is packaged inside - the E57Exception. The documentation for each function in the API declares which - ErrorCode values (inside an E57Exception) can possibly be thrown by the - function. Some API functions do not throw any E57Exceptions, and this is - documented by the designation "No E57Exceptions." in the "Exceptions:" section - of the function documentation page. - - If an API function does throw an E57Exception, the API user will rightfully be - concerned about the state of all of the API objects. There are four categories - of guarantee about the state of all objects that the API specifies. - - 1) All objects unchanged - all API objects are left in their original - state before the API function was called. This is the default guarantee, so if - there is no notation next to the ErrorCode in the "Exceptions:" section of the - function documentation page, the this category is implied. - - 2) XXX object modified, but consistent - The given object (or objects) - have been modified, but are left in a consistent state. - - 3) XXX object in undocumented state - The given object (or objects) may - have been left in an inconsistent state, and the only safe thing to do with them - is to call their destructor. - - 4) All objects in undocumented state - A very serious consistency error - has been detected, and the state of all API objects is suspect. The only safe - thing to do is to call their destructors. - - Almost all of the API functions can throw the following two ErrorCodes: - E57_ERROR_IMAGEFILE_NOT_OPEN and E57_ERROR_INTERNAL. In some E57 - implementations, the tree information may be stored on disk rather than in - memory. If the disk file is closed, even the most basic information may not be - available about nodes in the tree. So if the ImageFile is closed (by calling - ImageFile::close), the API user must be ready for many of the API functions to - throw E57Exception(E57_ERROR_IMAGEFILE_NOT_OPEN). Secondly, regarding the - E57_ERROR_INTERNAL error, there is a lot of consistency checking in the - Reference Implementation, and there may be much more added. Even if some API - routines do not now throw E57_ERROR_INTERNAL, they could some time in the - future, or in different implementations. So the right to throw - E57_ERROR_INTERNAL is reserved for every API function (except those that by - design can't throw E57Exceptions). + The E57Exception object communicates information about errors occurring in calls to the E57 API + functions. The error information is communicated from the location in the E57 implementation + where the error was detected to the @c catch statement in the code of the API user. The state of + E57Exception object has one mandatory field, the errorCode, and several optional fields that can + be set depending on the debug level of the E57 implementation. There are three optional fields + that encode the location in the source code of the E57 implementation where the error was + detected: @c sourceFileName, @c sourceFunctionName, and @c sourceLineNumber. Another optional + field is the @c context string that is human (or at least programmer) readable, which can capture + some variable values that might be useful in debugging. The E57Exception class is derived from + std::exception. So applications that only catch std::exceptions will detect E57Exceptions (but + with no information about the origin of the error). + + Many other APIs use error codes (defined integer constants) returned from the API functions to + communicate success or failure of the requested command. In contrast, the E57 API uses the C++ + exception mechanism to communicate failure (success is communicated by the return of the function + without exception). ::Success is never thrown. The API ErrorCode is packaged inside the + E57Exception. The documentation for each function in the API declares which ErrorCode values + (inside an E57Exception) can possibly be thrown by the function. Some API functions do not throw + any E57Exceptions, and this is documented by the designation "No E57Exceptions." in the + "Exceptions:" section of the function documentation page. + + If an API function does throw an E57Exception, the API user will rightfully be concerned about + the state of all of the API objects. There are four categories of guarantee about the state of + all objects that the API specifies. - It is strongly recommended that catch statements in user code that call API - functions catch E57Exception by reference (i.e. catch (E57Exception& - ex) and, if necessary, rethrow using the syntax that throws the currently - active exception (i.e. throw;). + 1) All objects unchanged - all API objects are left in their original state before the API + function was called. This is the default guarantee, so if there is no notation next to the + ErrorCode in the "Exceptions:" section of the function documentation page, the this category is + implied. + + 2) XXX object modified, but consistent - The given object (or objects) have been modified, + but are left in a consistent state. + + 3) XXX object in undocumented state - The given object (or objects) may have been left in + an inconsistent state, and the only safe thing to do with them is to call their destructor. + + 4) All objects in undocumented state - A very serious consistency error has been detected, + and the state of all API objects is suspect. The only safe thing to do is to call their + destructors. + + Almost all of the API functions can throw the following two ErrorCodes: ::ErrorImageFileNotOpen + and ::ErrorInternal. In some E57 implementations, the tree information may be stored on disk + rather than in memory. If the disk file is closed, even the most basic information may not be + available about nodes in the tree. So if the ImageFile is closed (by calling ImageFile::close), + the API user must be ready for many of the API functions to throw ::ErrorImageFileNotOpen. + Secondly, regarding the ErrorInternal error, there is a lot of consistency checking in the + Reference Implementation, and there may be much more added. Even if some API routines do not now + throw ::ErrorInternal, they could some time in the future, or in different implementations. So + the right to throw ::ErrorInternal is reserved for every API function (except those that by + design can't throw E57Exceptions). - Exceptions other that E57Exception may be thrown by calls to API functions (e.g. - std::bad_alloc). Production code will likely have catch handlers for these - exceptions as well. + It is strongly recommended that catch statements in user code that call API functions catch + E57Exception by reference (i.e. catch (E57Exception& ex) and, if necessary, rethrow + using the syntax that throws the currently active exception (i.e. throw;). - @see HelloWorld.cpp example + Exceptions other that E57Exception may be thrown by calls to API functions (e.g. std::bad_alloc). + Production code will likely have catch handlers for these exceptions as well. */ - //! @cond documentNonPublic The following isn't part of the API, and isn't - //! documented. - E57Exception::E57Exception( ErrorCode ecode, const std::string &context, const std::string &srcFileName, - int srcLineNumber, const char *srcFunctionName ) : - errorCode_( ecode ), - context_( context ), sourceFunctionName_( srcFunctionName ), sourceLineNumber_( srcLineNumber ) - { - sourceFileName_ = srcFileName.substr( srcFileName.find_last_of( "/\\" ) + 1 ); - } - //! @endcond + /*! + @fn const char *E57Exception::what() + @brief Get string description of exception category. + + @details + Returns "E57 Exception" for all E57Exceptions, no matter what the errorCode. + + @post No visible state is modified. + + @return The string description of exception category. + + @throw No E57Exceptions. + */ /*! - @brief Print error information on a given output stream. - @param [in] reportingFileName Name of file where catch statement caught + @fn void E57Exception::report( const char *reportingFileName, int reportingLineNumber, + const char *reportingFunctionName, std::ostream &os ) + @brief Print error information on a given output stream. + + @param [in] reportingFileName Name of file where catch statement caught the exception. NULL if + unknown. + @param [in] reportingLineNumber Number of source code line where catch statement caught the + exception. 0 if unknown. + @param [in] reportingFunctionName String name of function containing catch statement that caught the exception. NULL if unknown. - @param [in] reportingLineNumber Number of source code line where catch - statement caught the exception. 0 if unknown. - @param [in] reportingFunctionName String name of function containing catch - statement that caught the exception. NULL if unknown. - @param [in] os Output string to print a summary of exception information and - location of catch statement. + @param [in] os Output string to print a summary of exception information and location of catch + statement. + @details - The amount of information printed to output stream may depend on whether the E57 - implementation was built with debugging enabled. - @post No visible state is modified. - @throw No E57Exceptions. - @see E57ExceptionFunctions.cpp example, ErrorCode, HelloWorld.cpp example + The amount of information printed to output stream may depend on whether the E57 implementation + was built with debugging enabled. + + @post No visible state is modified. + + @throw No E57Exceptions. + + @see ErrorCode */ - void E57Exception::report( const char *reportingFileName, int reportingLineNumber, const char *reportingFunctionName, - std::ostream &os ) const - { - os << "**** Got an e57 exception: " << e57::Utilities::errorCodeToString( errorCode() ) << std::endl; - -#ifdef E57_DEBUG - os << " Debug info: " << std::endl; - os << " context: " << context_ << std::endl; - os << " sourceFunctionName: " << sourceFunctionName_ << std::endl; - if ( reportingFunctionName ) - os << " reportingFunctionName: " << reportingFunctionName << std::endl; - - /*** Add a line in error message that a smart editor (gnu emacs) can - * interpret as a link to the source code: */ - os << sourceFileName_ << "(" << sourceLineNumber_ << ") : error C" << errorCode_ << ": <--- occurred on" - << std::endl; - if ( reportingFileName ) - os << reportingFileName << "(" << reportingLineNumber << ") : error C0: <--- reported on" << std::endl; -#endif - } /*! - @brief Get numeric ::ErrorCode associated with the exception. - @post No visible state is modified. - @return The numeric ::ErrorCode associated with the exception. - @throw No E57Exceptions. - @see E57ExceptionFunctions.cpp example, E57Utilities::errorCodeToString, - ErrorCode + @fn ErrorCode E57Exception::errorCode() + @brief Get numeric ::ErrorCode associated with the exception. + + @post No visible state is modified. + + @return The numeric ::ErrorCode associated with the exception. + + @throw No E57Exceptions. + + @see E57Exception::errorStr, Utilities::errorCodeToString, ErrorCode */ - ErrorCode E57Exception::errorCode() const - { - return errorCode_; - } /*! - @brief Get human-readable string that describes the context of the error. - @details - The context string may include values in object state, or function arguments. - The format of the context string is not standardized. - However, in the Reference Implementation, many strings contain a sequence of " - VARNAME=VARVALUE" fields. - @post No visible state is modified. - @return The human-readable string that describes the context of the error. - @throw No E57Exceptions. - @see E57ExceptionsFunctions.cpp example + @fn std::string E57Exception::errorStr() + @brief Get error string associated with the exception. + + @post No visible state is modified. + + @return The error string associated with the exception. + + @throw No E57Exceptions. */ - std::string E57Exception::context() const - { - return context_; - } /*! - @brief Get string description of exception category. + @fn std::string E57Exception::context() + @brief Get human-readable string that describes the context of the error. + @details - Returns "E57 Exception" for all E57Exceptions, no matter what the errorCode. - @post No visible state is modified. - @return The string description of exception category. - @throw No E57Exceptions. - @see E57ExceptionsFunctions.cpp example + The context string may include values in object state, or function arguments. The format of the + context string is not standardized. However, in the Reference Implementation, many strings + contain a sequence of " VARNAME=VARVALUE" fields. + + @post No visible state is modified. + + @return The human-readable string that describes the context of the error. + + @throw No E57Exceptions. */ - const char *E57Exception::what() const noexcept - { - return "E57 exception"; - } /*! - @brief Get name of source file where exception occurred, for debugging. + @fn const char *E57Exception::sourceFileName() + @brief Get name of source file where exception occurred, for debugging. + @details - May return the value of the macro variable __FILE__ at the location where the - E57Exception was constructed. May return the empty string ("") in some E57 - implementations. - @post No visible state is modified. - @return The name of source file where exception occurred, for debugging. - @throw No E57Exceptions. - @see E57ExceptionsFunctions.cpp example + May return the value of the macro variable __FILE__ at the location where the E57Exception was + constructed. May return the empty string ("") in some E57 implementations. + + @post No visible state is modified. + + @return The name of source file where exception occurred, for debugging. + + @throw No E57Exceptions. */ - const char *E57Exception::sourceFileName() const - { - return sourceFileName_.c_str(); - } /*! - @brief Get name of function in source code where the error occurred , for + @fn const char *E57Exception::sourceFunctionName() + @brief Get name of function in source code where the error occurred , for debugging. + @details - May return the value of the macro variable __FUNCTION__ at the location where - the E57Exception was constructed. May return the empty string ("") in some E57 - implementations. - @post No visible state is modified. - @return The name of source code function where the error occurred , for - debugging. - @throw No E57Exceptions. + May return the value of the macro variable __FUNCTION__ at the location where the E57Exception + was constructed. May return the empty string ("") in some E57 implementations. + + @post No visible state is modified. + + @return The name of source code function where the error occurred , for debugging. + + @throw No E57Exceptions. */ - const char *E57Exception::sourceFunctionName() const - { - return sourceFunctionName_; - } /*! - @brief Get line number in source code file where exception occurred, for - debugging. + @fn int E57Exception::sourceLineNumber() + @brief Get line number in source code file where exception occurred, for debugging. + @details - May return the value of the macro variable __LINE__ at the location where the - E57Exception was constructed. May return the empty string ("") in some E57 - implementations. - @post No visible state is modified. - @return The line number in source code file where exception occurred, for - debugging. - @throw No E57Exceptions. + May return the value of the macro variable __LINE__ at the location where the E57Exception was + constructed. May return the empty string ("") in some E57 implementations. + + @post No visible state is modified. + + @return The line number in source code file where exception occurred, for debugging. + + @throw No E57Exceptions. */ - int E57Exception::sourceLineNumber() const - { - return sourceLineNumber_; - } //===================================================================================== /*! - @brief Get the version of ASTM E57 standard that the API implementation - supports, and library id string. - @param [out] astmMajor The major version number of the ASTM E57 standard - supported. - @param [out] astmMinor The minor version number of the ASTM E57 standard - supported. - @param [out] libraryId A string identifying the implementation of the API. - @details - Since the E57 implementation may be dynamically linked underneath the API, the - version string for the implementation and the ASTM version that it supports - can't be determined at compile-time. This function returns these identifiers - from the underlying implementation. - @throw No E57Exceptions. - */ - void Utilities::getVersions( int &astmMajor, int &astmMinor, std::string &libraryId ) - { - /// REVISION_ID should be passed from compiler command line - -#ifndef REVISION_ID -#error "Need to specify REVISION_ID on command line" -#endif + @brief Get short string description of an E57 ErrorCode. - astmMajor = E57_FORMAT_MAJOR; - astmMinor = E57_FORMAT_MINOR; - libraryId = REVISION_ID; - } + @param [in] ecode The numeric errorCode from an E57Exception. - /*! - @brief Get short string description of an E57 ErrorCode. - @param [in] ecode The numeric errorCode from an E57Exception. @details The errorCode is translated into a one-line English string. - @return English std::string describing error. - @throw No E57Exceptions. - @see E57Exception::errorCode + + @return English std::string describing error. + + @throw No E57Exceptions. + + @see E57Exception::errorCode */ - std::string Utilities::errorCodeToString( ErrorCode ecode ) + std::string Utilities::errorCodeToString( ErrorCode ecode ) noexcept { switch ( ecode ) { - // N.B. *** When changing error strings here, remember to update the - // Doxygen strings in E57Exception.h **** - case E57_SUCCESS: - return "operation was successful (E57_SUCCESS)"; - case E57_ERROR_BAD_CV_HEADER: - return "a CompressedVector binary header was bad " - "(E57_ERROR_BAD_CV_HEADER)"; - case E57_ERROR_BAD_CV_PACKET: - return "a CompressedVector binary packet was bad " - "(E57_ERROR_BAD_CV_PACKET)"; - case E57_ERROR_CHILD_INDEX_OUT_OF_BOUNDS: + case Success: + return "operation was successful (Success)"; + case ErrorBadCVHeader: + return "a CompressedVector binary header was bad (ErrorBadCVHeader)"; + case ErrorBadCVPacket: + return "a CompressedVector binary packet was bad (ErrorBadCVPacket)"; + case ErrorChildIndexOutOfBounds: return "a numerical index identifying a child was out of bounds " - "(E57_ERROR_CHILD_INDEX_OUT_OF_BOUNDS)"; - case E57_ERROR_SET_TWICE: - return "attempted to set an existing child element to a new value " - "(E57_ERROR_SET_TWICE)"; - case E57_ERROR_HOMOGENEOUS_VIOLATION: - return "attempted to add an E57 Element that would have made the " - "children of a " - "homogeneous Vector have different types " - "(E57_ERROR_HOMOGENEOUS_VIOLATION)"; - case E57_ERROR_VALUE_NOT_REPRESENTABLE: + "(ErrorChildIndexOutOfBounds)"; + case ErrorSetTwice: + return "attempted to set an existing child element to a new value (ErrorSetTwice)"; + case ErrorHomogeneousViolation: + return "attempted to add an E57 Element that would have made the children of a " + "homogeneous Vector have " + "different types (E57_ERROR_HOMOGENEOUS_VIOLATION)"; + case ErrorValueNotRepresentable: return "a value could not be represented in the requested type " - "(E57_ERROR_VALUE_NOT_REPRESENTABLE)"; - case E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE: - return "after scaling the result could not be represented in the " - "requested type " - "(E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE)"; - case E57_ERROR_REAL64_TOO_LARGE: - return "a 64 bit IEEE float was too large to store in a 32 bit IEEE " - "float " - "(E57_ERROR_REAL64_TOO_LARGE)"; - case E57_ERROR_EXPECTING_NUMERIC: - return "Expecting numeric representation in user's buffer, found " - "ustring " - "(E57_ERROR_EXPECTING_NUMERIC)"; - case E57_ERROR_EXPECTING_USTRING: - return "Expecting string representation in user's buffer, found " - "numeric " - "(E57_ERROR_EXPECTING_USTRING)"; - case E57_ERROR_INTERNAL: - return "An unrecoverable inconsistent internal state was detected " - "(E57_ERROR_INTERNAL)"; - case E57_ERROR_BAD_XML_FORMAT: - return "E57 primitive not encoded in XML correctly " - "(E57_ERROR_BAD_XML_FORMAT)"; - case E57_ERROR_XML_PARSER: - return "XML not well formed (E57_ERROR_XML_PARSER)"; - case E57_ERROR_BAD_API_ARGUMENT: - return "bad API function argument provided by user " - "(E57_ERROR_BAD_API_ARGUMENT)"; - case E57_ERROR_FILE_IS_READ_ONLY: - return "can't modify read only file (E57_ERROR_FILE_IS_READ_ONLY)"; - case E57_ERROR_BAD_CHECKSUM: - return "checksum mismatch, file is corrupted (E57_ERROR_BAD_CHECKSUM)"; - case E57_ERROR_OPEN_FAILED: - return "open() failed (E57_ERROR_OPEN_FAILED)"; - case E57_ERROR_CLOSE_FAILED: - return "close() failed (E57_ERROR_CLOSE_FAILED)"; - case E57_ERROR_READ_FAILED: - return "read() failed (E57_ERROR_READ_FAILED)"; - case E57_ERROR_WRITE_FAILED: - return "write() failed (E57_ERROR_WRITE_FAILED)"; - case E57_ERROR_LSEEK_FAILED: - return "lseek() failed (E57_ERROR_LSEEK_FAILED)"; - case E57_ERROR_PATH_UNDEFINED: - return "E57 element path well formed but not defined " - "(E57_ERROR_PATH_UNDEFINED)"; - case E57_ERROR_BAD_BUFFER: - return "bad SourceDestBuffer (E57_ERROR_BAD_BUFFER)"; - case E57_ERROR_NO_BUFFER_FOR_ELEMENT: - return "no buffer specified for an element in CompressedVectorNode " - "during write " - "(E57_ERROR_NO_BUFFER_FOR_ELEMENT)"; - case E57_ERROR_BUFFER_SIZE_MISMATCH: - return "SourceDestBuffers not all same size " - "(E57_ERROR_BUFFER_SIZE_MISMATCH)"; - case E57_ERROR_BUFFER_DUPLICATE_PATHNAME: + "(ErrorValueNotRepresentable)"; + case ErrorScaledValueNotRepresentable: + return "after scaling the result could not be represented in the requested type " + "(ErrorScaledValueNotRepresentable)"; + case ErrorReal64TooLarge: + return "a 64 bit IEEE float was too large to store in a 32 bit IEEE float " + "(ErrorReal64TooLarge)"; + case ErrorExpectingNumeric: + return "Expecting numeric representation in user's buffer, found ustring " + "(ErrorExpectingNumeric)"; + case ErrorExpectingUString: + return "Expecting string representation in user's buffer, found numeric " + "(ErrorExpectingUString)"; + case ErrorInternal: + return "An unrecoverable inconsistent internal state was detected (ErrorInternal)"; + case ErrorBadXMLFormat: + return "E57 primitive not encoded in XML correctly (ErrorBadXMLFormat)"; + case ErrorXMLParser: + return "XML not well formed (ErrorXMLParser)"; + case ErrorBadAPIArgument: + return "bad API function argument provided by user (ErrorBadAPIArgument)"; + case ErrorFileReadOnly: + return "can't modify read only file (ErrorFileReadOnly)"; + case ErrorBadChecksum: + return "checksum mismatch, file is corrupted (ErrorBadChecksum)"; + case ErrorOpenFailed: + return "open() failed (ErrorOpenFailed)"; + case ErrorCloseFailed: + return "close() failed (ErrorCloseFailed)"; + case ErrorReadFailed: + return "read() failed (ErrorReadFailed)"; + case ErrorWriteFailed: + return "write() failed (ErrorWriteFailed)"; + case ErrorSeekFailed: + return "lseek() failed (ErrorSeekFailed)"; + case ErrorPathUndefined: + return "E57 element path well formed but not defined (ErrorPathUndefined)"; + case ErrorBadBuffer: + return "bad SourceDestBuffer (ErrorBadBuffer)"; + case ErrorNoBufferForElement: + return "no buffer specified for an element in CompressedVectorNode during write " + "(ErrorNoBufferForElement)"; + case ErrorBufferSizeMismatch: + return "SourceDestBuffers not all same size (ErrorBufferSizeMismatch)"; + case ErrorBufferDuplicatePathName: return "duplicate pathname in CompressedVectorNode read/write " - "(E57_ERROR_BUFFER_DUPLICATE_PATHNAME)"; - case E57_ERROR_BAD_FILE_SIGNATURE: - return "file signature not " - "ASTM-E57" - " (E57_ERROR_BAD_FILE_SIGNATURE)"; - case E57_ERROR_UNKNOWN_FILE_VERSION: - return "incompatible file version (E57_ERROR_UNKNOWN_FILE_VERSION)"; - case E57_ERROR_BAD_FILE_LENGTH: - return "size in file header not same as actual " - "(E57_ERROR_BAD_FILE_LENGTH)"; - case E57_ERROR_XML_PARSER_INIT: - return "XML parser failed to initialize (E57_ERROR_XML_PARSER_INIT)"; - case E57_ERROR_DUPLICATE_NAMESPACE_PREFIX: - return "namespace prefix already defined " - "(E57_ERROR_DUPLICATE_NAMESPACE_PREFIX)"; - case E57_ERROR_DUPLICATE_NAMESPACE_URI: - return "namespace URI already defined " - "(E57_ERROR_DUPLICATE_NAMESPACE_URI)"; - case E57_ERROR_BAD_PROTOTYPE: - return "bad prototype in CompressedVectorNode " - "(E57_ERROR_BAD_PROTOTYPE)"; - case E57_ERROR_BAD_CODECS: - return "bad codecs in CompressedVectorNode (E57_ERROR_BAD_CODECS)"; - case E57_ERROR_VALUE_OUT_OF_BOUNDS: - return "element value out of min/max bounds " - "(E57_ERROR_VALUE_OUT_OF_BOUNDS)"; - case E57_ERROR_CONVERSION_REQUIRED: - return "conversion required to assign element value, but not " - "requested " - "(E57_ERROR_CONVERSION_REQUIRED)"; - case E57_ERROR_BAD_PATH_NAME: - return "E57 path name is not well formed (E57_ERROR_BAD_PATH_NAME)"; - case E57_ERROR_NOT_IMPLEMENTED: - return "functionality not implemented (E57_ERROR_NOT_IMPLEMENTED)"; - case E57_ERROR_BAD_NODE_DOWNCAST: - return "bad downcast from Node to specific node type " - "(E57_ERROR_BAD_NODE_DOWNCAST)"; - case E57_ERROR_WRITER_NOT_OPEN: - return "CompressedVectorWriter is no longer open " - "(E57_ERROR_WRITER_NOT_OPEN)"; - case E57_ERROR_READER_NOT_OPEN: - return "CompressedVectorReader is no longer open " - "(E57_ERROR_READER_NOT_OPEN)"; - case E57_ERROR_NODE_UNATTACHED: - return "node is not yet attached to tree of ImageFile " - "(E57_ERROR_NODE_UNATTACHED)"; - case E57_ERROR_ALREADY_HAS_PARENT: - return "node already has a parent (E57_ERROR_ALREADY_HAS_PARENT)"; - case E57_ERROR_DIFFERENT_DEST_IMAGEFILE: + "(ErrorBufferDuplicatePathName)"; + case ErrorBadFileSignature: + return "file signature not ASTM-E57 (ErrorBadFileSignature)"; + case ErrorUnknownFileVersion: + return "incompatible file version (ErrorUnknownFileVersion)"; + case ErrorBadFileLength: + return "size in file header not same as actual (ErrorBadFileLength)"; + case ErrorXMLParserInit: + return "XML parser failed to initialize (ErrorXMLParserInit)"; + case ErrorDuplicateNamespacePrefix: + return "namespace prefix already defined (ErrorDuplicateNamespacePrefix)"; + case ErrorDuplicateNamespaceURI: + return "namespace URI already defined (ErrorDuplicateNamespaceURI)"; + case ErrorBadPrototype: + return "bad prototype in CompressedVectorNode (ErrorBadPrototype)"; + case ErrorBadCodecs: + return "bad codecs in CompressedVectorNode (ErrorBadCodecs)"; + case ErrorValueOutOfBounds: + return "element value out of min/max bounds (ErrorValueOutOfBounds)"; + case ErrorConversionRequired: + return "conversion required to assign element value, but not requested " + "(ErrorConversionRequired)"; + case ErrorBadPathName: + return "E57 path name is not well formed (ErrorBadPathName)"; + case ErrorNotImplemented: + return "functionality not implemented (ErrorNotImplemented)"; + case ErrorBadNodeDowncast: + return "bad downcast from Node to specific node type (ErrorBadNodeDowncast)"; + case ErrorWriterNotOpen: + return "CompressedVectorWriter is no longer open (ErrorWriterNotOpen)"; + case ErrorReaderNotOpen: + return "CompressedVectorReader is no longer open (ErrorReaderNotOpen)"; + case ErrorNodeUnattached: + return "node is not yet attached to tree of ImageFile (ErrorNodeUnattached)"; + case ErrorAlreadyHasParent: + return "node already has a parent (ErrorAlreadyHasParent)"; + case ErrorDifferentDestImageFile: return "nodes were constructed with different destImageFiles " - "(E57_ERROR_DIFFERENT_DEST_IMAGEFILE)"; - case E57_ERROR_IMAGEFILE_NOT_OPEN: - return "destImageFile is no longer open " - "(E57_ERROR_IMAGEFILE_NOT_OPEN)"; - case E57_ERROR_BUFFERS_NOT_COMPATIBLE: + "(ErrorDifferentDestImageFile)"; + case ErrorImageFileNotOpen: + return "destImageFile is no longer open (ErrorImageFileNotOpen)"; + case ErrorBuffersNotCompatible: return "SourceDestBuffers not compatible with previously given ones " - "(E57_ERROR_BUFFERS_NOT_COMPATIBLE)"; - case E57_ERROR_TOO_MANY_WRITERS: - return "too many open CompressedVectorWriters of an ImageFile " - "(E57_ERROR_TOO_MANY_WRITERS)"; - case E57_ERROR_TOO_MANY_READERS: - return "too many open CompressedVectorReaders of an ImageFile " - "(E57_ERROR_TOO_MANY_READERS)"; - case E57_ERROR_BAD_CONFIGURATION: - return "bad configuration string (E57_ERROR_BAD_CONFIGURATION)"; - case E57_ERROR_INVARIANCE_VIOLATION: - return "class invariance constraint violation in debug mode " - "(E57_ERROR_INVARIANCE_VIOLATION)"; + "(ErrorBuffersNotCompatible)"; + case ErrorTooManyWriters: + return "too many open CompressedVectorWriters of an ImageFile (ErrorTooManyWriters)"; + case ErrorTooManyReaders: + return "too many open CompressedVectorReaders of an ImageFile (ErrorTooManyReaders)"; + case ErrorBadConfiguration: + return "bad configuration string (ErrorBadConfiguration)"; + case ErrorInvarianceViolation: + return "class invariance constraint violation in debug mode (ErrorInvarianceViolation)"; + case ErrorInvalidNodeType: + return "an invalid node type was passed in Data3D pointFields"; + case ErrorInvalidData3DValue: + return "an invalid value was passed in Data3D pointFields"; + default: return "unknown error (" + std::to_string( ecode ) + ")"; } } - } diff --git a/src/3rdParty/libE57Format/src/E57Format.cpp b/src/3rdParty/libE57Format/src/E57Format.cpp deleted file mode 100644 index 47ff2e8b8fdd6..0000000000000 --- a/src/3rdParty/libE57Format/src/E57Format.cpp +++ /dev/null @@ -1,4891 +0,0 @@ -/* - * E57Format.cpp - implementation of public functions of the E57 format - * Reference Implementation. - * - * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) - * Modified work Copyright 2018 - 2020 Andy Maloney - * - * Permission is hereby granted, free of charge, to any person or organization - * obtaining a copy of the software and accompanying documentation covered by - * this license (the "Software") to use, reproduce, display, distribute, - * execute, and transmit the Software, and to prepare derivative works of the - * Software, and to permit third-parties to whom the Software is furnished to - * do so, all subject to the following: - * - * The copyright notices in the Software and this entire statement, including - * the above license grant, this restriction and the following disclaimer, - * must be included in all copies of the Software, in whole or in part, and - * all derivative works of the Software, unless such copies or derivative - * works are solely in the form of machine-executable object code generated by - * a source language processor. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT - * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE - * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - */ - -//! @file E57Format.cpp - -#include "BlobNodeImpl.h" -#include "CompressedVectorNodeImpl.h" -#include "CompressedVectorReaderImpl.h" -#include "CompressedVectorWriterImpl.h" -#include "FloatNodeImpl.h" -#include "ImageFileImpl.h" -#include "IntegerNodeImpl.h" -#include "ScaledIntegerNodeImpl.h" -#include "SourceDestBufferImpl.h" -#include "StringNodeImpl.h" -#include "VectorNodeImpl.h" - -using namespace e57; - -/*! -@brief Check whether Node class invariant is true -@param [in] doRecurse If true, also check invariants of all children or -sub-objects recursively. -@param [in] doDowncast If true, also check any invariants of the actual -derived type in addition to the generic node invariants. -@details -This function checks at least the assertions in the documented class invariant -description (see class reference page for this object). Other internal -invariants that are implementation-dependent may also be checked. If any -invariant clause is violated, an E57Exception with errorCode of -E57_ERROR_INVARIANCE_VIOLATION is thrown. - -Specifying doRecurse=true only makes sense if doDowncast=true is also specified -(the generic Node has no way to access any children). Checking the invariant -recursively may be expensive if the tree is large, so should be used -judiciously, in debug versions of the application. -@post No visible state is modified. -@throw ::E57_ERROR_INVARIANCE_VIOLATION or any other E57 ErrorCode -@see Class Invariant section in Node, -IntegerNode::checkInvariant, ScaledIntegerNode::checkInvariant, -FloatNode::checkInvariant, BlobNode::checkInvariant, -StructureNode::checkInvariant, VectorNode::checkInvariant, -CompressedVectorNode::checkInvariant -*/ -void Node::checkInvariant( bool doRecurse, bool doDowncast ) -{ - ImageFile imf = destImageFile(); - - // If destImageFile not open, can't test invariant (almost every call would - // throw) - if ( !imf.isOpen() ) - { - return; - } - - // Parent attachment state is same as this attachment state - if ( isAttached() != parent().isAttached() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Parent destination ImageFile is same as this - if ( imf != parent().destImageFile() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // If this is the ImageFile root node - if ( *this == imf.root() ) - { - // Must be attached - if ( !isAttached() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Must be is a root node - if ( !isRoot() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - - // If this is a root node - if ( isRoot() ) - { - // Absolute pathName is "/" - if ( pathName() != "/" ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // parent() returns this node - if ( *this != parent() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - else - { - // Non-root can't be own parent - if ( *this == parent() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // pathName is concatenation of parent pathName and this elementName - if ( parent().isRoot() ) - { - if ( pathName() != "/" + elementName() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - else - { - if ( pathName() != parent().pathName() + "/" + elementName() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - - // Non-root nodes must be children of either a VectorNode or StructureNode - if ( parent().type() == E57_VECTOR ) - { - VectorNode v = static_cast( parent() ); - - // Must be defined in parent VectorNode with this elementName - if ( !v.isDefined( elementName() ) ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Getting child of parent with this elementName must return this - if ( v.get( elementName() ) != *this ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - else if ( parent().type() == E57_STRUCTURE ) - { - StructureNode s = static_cast( parent() ); - - // Must be defined in parent VectorNode with this elementName - if ( !s.isDefined( elementName() ) ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Getting child of parent with this elementName must return this - if ( s.get( elementName() ) != *this ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - else - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - - // If this is attached - if ( isAttached() ) - { - // Get root of this - Node n = *this; - while ( !n.isRoot() ) - { - n = n.parent(); - } - - // If in tree of ImageFile (could be in a prototype instead) - if ( n == imf.root() ) - { - // pathName must be defined - if ( !imf.root().isDefined( pathName() ) ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Getting by absolute pathName must be this - if ( imf.root().get( pathName() ) != *this ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - } - - // If requested, check invariants of derived types: - if ( doDowncast ) - { - switch ( type() ) - { - case E57_STRUCTURE: - { - StructureNode s( *this ); - s.checkInvariant( doRecurse, false ); - } - break; - case E57_VECTOR: - { - VectorNode v( *this ); - v.checkInvariant( doRecurse, false ); - } - break; - case E57_COMPRESSED_VECTOR: - { - CompressedVectorNode cv( *this ); - cv.checkInvariant( doRecurse, false ); - } - break; - case E57_INTEGER: - { - IntegerNode i( *this ); - i.checkInvariant( doRecurse, false ); - } - break; - case E57_SCALED_INTEGER: - { - ScaledIntegerNode si( *this ); - si.checkInvariant( doRecurse, false ); - } - break; - case E57_FLOAT: - { - FloatNode f( *this ); - f.checkInvariant( doRecurse, false ); - } - break; - case E57_STRING: - { - StringNode s( *this ); - s.checkInvariant( doRecurse, false ); - } - break; - case E57_BLOB: - { - BlobNode b( *this ); - b.checkInvariant( doRecurse, false ); - } - break; - default: - break; - } - } -} - -/*! -@class Node -@brief Generic handle to any of the 8 types of E57 element objects. -@details -A Node is a generic handle to an underlying object that is any of the eight type -of E57 element objects. Each of the eight node types support the all the -functions of the Node class. A Node is a vertex in a tree (acyclic graph), which -is a hierarchical organization of nodes. At the top of the hierarchy is a single -root Node. If a Node is a container type (StructureNode, VectorNode, -CompressedVectorNode) it may have child nodes. The following are non-container -type nodes (also known as terminal nodes): IntegerNode, ScaledIntegerNode, -FloatNode, StringNode, BlobNode. Terminal nodes store various types of values -and cannot have children. Each Node has an elementName, which is a string that -uniquely identifies it within the children of its parent. Children of a -StructureNode have elementNames that are explicitly given by the API user. -Children of a VectorNode or CompressedVectorNode have element names that are -string reorientations of the Node's positional index, starting at "0". A path -name is a sequence elementNames (divided by "/") that must be traversed to get -from a Node to one of its descendents. - -Data is organized in an E57 format file (an ImageFile) hierarchically. -Each ImageFile has a predefined root node that other nodes can be attached to as -children (either directly or indirectly). A Node can exist temporarily without -being attached to an ImageFile, however the state will not be saved in the -associated file, and the state will be lost if the program exits. - -A handle to a generic Node may be safely be converted to and from a handle to -the Node's true underlying type. Since an attempt to convert a generic Node to a -incorrect handle type will fail with an exception, the true type should be -interrogated beforehand. - -Due to the set-once design of the Foundation API, terminal nodes are immutable -(i.e. their values and attributes can't change after creation). Once a -parent-child relationship has been established, it cannot be changed. - -Only generic operations are available for a Node, to access more specific -operations (e.g. StructureNode::childCount) the generic handle must be converted -to the node type of the underlying object. This conversion is done in a -type-safe way using "downcasting" (see discussion below). - -@section node_Downcasting Downcasting -The conversion from a general handle type to a specific handle type is called -"downcasting". Each of the 8 specific node types have a downcast function (see -IntegerNode::IntegerNode(const Node&) for example). If a downcast is requested -to an incorrect type (e.g. taking a Node handle that is actually a FloatNode and -trying to downcast it to a IntegerNode), an E57Exception is thrown with an -ErrorCode of E57_ERROR_BAD_NODE_DOWNCAST. Depending on the program design, -throwing a bad downcast exception might be acceptable, if an element must be a -specific type and no recovery is possible. If a standard requires an element be -one several types, then Node::type() should be used to interrogate the type in -an @c if or @c switch statement. Downcasting is "dangerous" (can fail with an -exception) so the API requires the programmer to explicitly call the downcast -functions rather than have the c++ compiler insert them automatically. - -@section node_Upcasting Upcasting -The conversion of a specific node handle (e.g. IntegerNode) to a general Node -handle is called "upcasting". Each of the 8 specific node types have an upcast -function (see IntegerNode::operator Node() for example). Upcasting is "safe" -(can't cause an exception) so the API allows the c++ compiler to insert them -automatically. Upcasting is useful if you have a specific node handle and want -to call a function that takes a generic Node handle argument. In this case, the -function can be called with the specific handle and the compiler will -automatically insert the upcast conversion. This implicit conversion allows one -function, with an argument of type Node, to handle operations that apply to all -8 types of nodes (e.g. StructureNode::set()). - -@section node_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Foundation.cpp -@skip begin Node::checkInvariant -@skip checkInvariant( -@until end Node::checkInvariant - -@see StructureNode, VectorNode, CompressedVectorNode, IntegerNode, -ScaledIntegerNode, FloatNode, StringNode, BlobNode -*/ - -//! @brief Check whether StructureNode class invariant is true -//! @copydetails IntegerNode::checkInvariant() -void StructureNode::checkInvariant( bool doRecurse, bool doUpcast ) -{ - // If destImageFile not open, can't test invariant (almost every call would - // throw) - if ( !destImageFile().isOpen() ) - { - return; - } - - // If requested, call Node::checkInvariant - if ( doUpcast ) - { - static_cast( *this ).checkInvariant( false, false ); - } - - // Check each child - for ( int64_t i = 0; i < childCount(); i++ ) - { - Node child = get( i ); - - // If requested, check children recursively - if ( doRecurse ) - { - child.checkInvariant( doRecurse, true ); - } - - // Child's parent must be this - if ( static_cast( *this ) != child.parent() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Child's elementName must be defined - if ( !isDefined( child.elementName() ) ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Getting child by element name must yield same child - Node n = get( child.elementName() ); - if ( n != child ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } -} - -//! @brief Check whether VectorNode class invariant is true -//! @copydetails IntegerNode::checkInvariant() -void VectorNode::checkInvariant( bool doRecurse, bool doUpcast ) -{ - // If destImageFile not open, can't test invariant (almost every call would - // throw) - if ( !destImageFile().isOpen() ) - { - return; - } - - // If requested, call Node::checkInvariant - if ( doUpcast ) - { - static_cast( *this ).checkInvariant( false, false ); - } - - // Check each child - for ( int64_t i = 0; i < childCount(); i++ ) - { - Node child = get( i ); - - // If requested, check children recursively - if ( doRecurse ) - { - child.checkInvariant( doRecurse, true ); - } - - // Child's parent must be this - if ( static_cast( *this ) != child.parent() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Child's elementName must be defined - if ( !isDefined( child.elementName() ) ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Getting child by element name must yield same child - Node n = get( child.elementName() ); - if ( n != child ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } -} - -//! @brief Check whether CompressedVectorNode class invariant is true -//! @copydetails IntegerNode::checkInvariant() -void CompressedVectorNode::checkInvariant( bool doRecurse, bool doUpcast ) -{ - // If destImageFile not open, can't test invariant (almost every call would - // throw) - if ( !destImageFile().isOpen() ) - { - return; - } - - // If requested, call Node::checkInvariant - if ( doUpcast ) - { - static_cast( *this ).checkInvariant( false, false ); - } - - // Check prototype is good Node - prototype().checkInvariant( doRecurse ); - - // prototype attached state not same as this attached state - if ( prototype().isAttached() != isAttached() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // prototype not root - if ( !prototype().isRoot() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // prototype dest ImageFile not same as this dest ImageFile - if ( prototype().destImageFile() != destImageFile() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Check codecs is good Node - codecs().checkInvariant( doRecurse ); - - // codecs attached state not same as this attached state - if ( codecs().isAttached() != isAttached() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // codecs not root - if ( !codecs().isRoot() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // codecs dest ImageFile not same as this dest ImageFile - if ( codecs().destImageFile() != destImageFile() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } -} -/*! -@brief Check whether IntegerNode class invariant is true -@param [in] doRecurse If true, also check invariants of all children or -sub-objects recursively. -@param [in] doUpcast If true, also check invariants of the generic Node -class. -@details -This function checks at least the assertions in the documented class invariant -description (see class reference page for this object). Other internal -invariants that are implementation-dependent may also be checked. If any -invariant clause is violated, an E57Exception with errorCode of -E57_ERROR_INVARIANCE_VIOLATION is thrown. - -Checking the invariant recursively may be expensive if the tree is large, so -should be used judiciously, in debug versions of the application. -@post No visible state is modified. -@throw ::E57_ERROR_INVARIANCE_VIOLATION or any other E57 ErrorCode -*/ -void IntegerNode::checkInvariant( bool /*doRecurse*/, bool doUpcast ) -{ - // If destImageFile not open, can't test invariant (almost every call would - // throw) - if ( !destImageFile().isOpen() ) - { - return; - } - - // If requested, call Node::checkInvariant - if ( doUpcast ) - { - static_cast( *this ).checkInvariant( false, false ); - } - - if ( value() < minimum() || value() > maximum() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } -} - -//! @brief Check whether ScaledIntegerNode class invariant is true -//! @copydetails IntegerNode::checkInvariant() -void ScaledIntegerNode::checkInvariant( bool /*doRecurse*/, bool doUpcast ) -{ - // If destImageFile not open, can't test invariant (almost every call would - // throw) - if ( !destImageFile().isOpen() ) - { - return; - } - - // If requested, call Node::checkInvariant - if ( doUpcast ) - { - static_cast( *this ).checkInvariant( false, false ); - } - - // If value is out of bounds - if ( rawValue() < minimum() || rawValue() > maximum() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // If scale is zero - if ( scale() == 0 ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // If scaled value is not calculated correctly - if ( scaledValue() != rawValue() * scale() + offset() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } -} -//! @brief Check whether FloatNode class invariant is true -//! @copydetails IntegerNode::checkInvariant() -void FloatNode::checkInvariant( bool /*doRecurse*/, bool doUpcast ) -{ - // If destImageFile not open, can't test invariant (almost every call would - // throw) - if ( !destImageFile().isOpen() ) - { - return; - } - - // If requested, call Node::checkInvariant - if ( doUpcast ) - { - static_cast( *this ).checkInvariant( false, false ); - } - - if ( precision() == E57_SINGLE ) - { - if ( static_cast( minimum() ) < E57_FLOAT_MIN || static_cast( maximum() ) > E57_FLOAT_MAX ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - - // If value is out of bounds - if ( value() < minimum() || value() > maximum() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } -} -//! @brief Check whether StringNode class invariant is true -//! @copydetails IntegerNode::checkInvariant() -void StringNode::checkInvariant( bool /*doRecurse*/, bool doUpcast ) -{ - // If destImageFile not open, can't test invariant (almost every call would - // throw) - if ( !destImageFile().isOpen() ) - { - return; - } - - // If requested, call Node::checkInvariant - if ( doUpcast ) - { - static_cast( *this ).checkInvariant( false, false ); - } - /// ? check legal UTF-8 -} -//! @brief Check whether BlobNode class invariant is true -//! @copydetails IntegerNode::checkInvariant() -void BlobNode::checkInvariant( bool /*doRecurse*/, bool doUpcast ) -{ - // If destImageFile not open, can't test invariant (almost every call would - // throw) - if ( !destImageFile().isOpen() ) - { - return; - } - - // If requested, call Node::checkInvariant - if ( doUpcast ) - { - static_cast( *this ).checkInvariant( false, false ); - } - - if ( byteCount() < 0 ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } -} -/*! -@brief Check whether CompressedVectorReader class invariant is true -@param [in] doRecurse If true, also check invariants of all children or -sub-objects recursively. -@details -This function checks at least the assertions in the documented class invariant -description (see class reference page for this object). Other internal -invariants that are implementation-dependent may also be checked. If any -invariant clause is violated, an E57Exception with errorCode of -E57_ERROR_INVARIANCE_VIOLATION is thrown. -@post No visible state is modified. -*/ -void CompressedVectorReader::checkInvariant( bool /*doRecurse*/ ) -{ - // If this CompressedVectorReader is not open, can't test invariant (almost - // every call would throw) - if ( !isOpen() ) - { - return; - } - - CompressedVectorNode cv = compressedVectorNode(); - ImageFile imf = cv.destImageFile(); - - // If destImageFile not open, can't test invariant (almost every call would - // throw) - if ( !imf.isOpen() ) - { - return; - } - - // Associated CompressedVectorNode must be attached to ImageFile - if ( !cv.isAttached() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Dest ImageFile must have at least 1 reader (this one) - if ( imf.readerCount() < 1 ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Dest ImageFile can't have any writers - if ( imf.writerCount() != 0 ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } -} - -//! @brief Check whether CompressedVectorWriter class invariant is true -//! @copydetails CompressedVectorReader::checkInvariant -void CompressedVectorWriter::checkInvariant( bool /*doRecurse*/ ) -{ - // If this CompressedVectorWriter is not open, can't test invariant (almost - // every call would throw) - if ( !isOpen() ) - { - return; - } - - CompressedVectorNode cv = compressedVectorNode(); - ImageFile imf = cv.destImageFile(); - - // If destImageFile not open, can't test invariant (almost every call would - // throw) - if ( !imf.isOpen() ) - { - return; - } - - // Associated CompressedVectorNode must be attached to ImageFile - if ( !cv.isAttached() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Dest ImageFile must be writable - if ( !imf.isWritable() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Dest ImageFile must have exactly 1 writer (this one) - if ( imf.writerCount() != 1 ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Dest ImageFile can't have any readers - if ( imf.readerCount() != 0 ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } -} - -/*! -@brief Check whether ImageFile class invariant is true -@param [in] doRecurse If true, also check invariants of all children or -sub-objects recursively. -@details -This function checks at least the assertions in the documented class invariant -description (see class reference page for this object). Other internal -invariants that are implementation-dependent may also be checked. If any -invariant clause is violated, an E57Exception with errorCode of -E57_ERROR_INVARIANCE_VIOLATION is thrown. - -Checking the invariant recursively may be expensive if the tree is large, so -should be used judiciously, in debug versions of the application. -@post No visible state is modified. -@throw ::E57_ERROR_INVARIANCE_VIOLATION or any other E57 ErrorCode -@see Node::checkInvariant -*/ -void ImageFile::checkInvariant( bool doRecurse ) const -{ - // If this ImageFile is not open, can't test invariant (almost every call - // would throw) - if ( !isOpen() ) - { - return; - } - - // root() node must be a root node - if ( !root().isRoot() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Can't have empty fileName - if ( fileName().empty() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - int wCount = writerCount(); - int rCount = readerCount(); - - // Can't have negative number of readers - if ( rCount < 0 ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Can't have negative number of writers - if ( wCount < 0 ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Can't have more than one writer - if ( 1 < wCount ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // If have writer - if ( wCount > 0 ) - { - // Must be in write-mode - if ( !isWritable() ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - - // Can't have any readers - if ( rCount > 0 ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - - // Extension prefixes and URIs are unique - const size_t eCount = extensionsCount(); - for ( size_t i = 0; i < eCount; i++ ) - { - for ( size_t j = i + 1; j < eCount; j++ ) - { - if ( extensionsPrefix( i ) == extensionsPrefix( j ) ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - if ( extensionsUri( i ) == extensionsUri( j ) ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - } - - // Verify lookup functions are correct - for ( size_t i = 0; i < eCount; i++ ) - { - ustring goodPrefix = extensionsPrefix( i ); - ustring goodUri = extensionsUri( i ); - ustring prefix; - ustring uri; - if ( !extensionsLookupPrefix( goodPrefix, uri ) ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - if ( uri != goodUri ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - if ( !extensionsLookupUri( goodUri, prefix ) ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - if ( prefix != goodPrefix ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - } - - // If requested, check all objects "below" this one - if ( doRecurse ) - { - root().checkInvariant( doRecurse ); - } -} - -//! @brief Check whether SourceDestBuffer class invariant is true -void SourceDestBuffer::checkInvariant( bool /*doRecurse*/ ) const -{ - // Stride must be >= a memory type dependent value - size_t min_stride = 0; - switch ( memoryRepresentation() ) - { - case E57_INT8: - case E57_UINT8: - case E57_BOOL: - min_stride = 1; - break; - case E57_INT16: - case E57_UINT16: - min_stride = 2; - break; - case E57_INT32: - case E57_UINT32: - case E57_REAL32: - min_stride = 4; - break; - case E57_INT64: - case E57_REAL64: - min_stride = 8; - break; - case E57_USTRING: - min_stride = sizeof( ustring ); - break; - default: - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } - if ( stride() < min_stride ) - { - throw E57_EXCEPTION1( E57_ERROR_INVARIANCE_VIOLATION ); - } -} - -/*! -@brief Return the NodeType of a generic Node. -@details This function allows the actual node type to be interrogated before -upcasting the handle to the actual node type (see Upcasting and Dowcasting -section in Node). -@return The NodeType of a generic Node, which may be one of the following -NodeType enumeration values: -::E57_STRUCTURE, ::E57_VECTOR, ::E57_COMPRESSED_VECTOR, ::E57_INTEGER, -::E57_SCALED_INTEGER, -::E57_FLOAT, ::E57_STRING, ::E57_BLOB. -@post No visible state is modified. -@see NodeType, upcast/dowcast discussion in Node -*/ -NodeType Node::type() const -{ - return impl_->type(); -} - -/*! -@brief Is this a root node. -@details A root node has itself as a parent (it is not a child of any node). -Newly constructed nodes (before they are inserted into an ImageFile tree) start -out as root nodes. It is possible to temporarily create small trees that are -unattached to any ImageFile. In these temporary trees, the top-most node will be -a root node. After the tree is attached to the ImageFile tree, the only root -node will be the pre-created one of the ImageTree (the one returned by -ImageFile::root). The concept of @em attachment is slightly larger than that of -the parent-child relationship (see Node::isAttached and -CompressedVectorNode::CompressedVectorNode for more details). -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return true if this node is a root node. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see Node::parent, Node::isAttached, CompressedVectorNode::CompressedVectorNode -*/ -bool Node::isRoot() const -{ - return impl_->isRoot(); -} - -/*! -@brief Return parent of node, or self if a root node. -@details Nodes are organized into trees (acyclic graphs) with a distinguished -node (the "top-most" node) called the root node. A parent-child relationship is -established between nodes to form a tree. Nodes can have zero or one parent. -Nodes with zero parents are called root nodes. -In the API, if a node has zero parents it is represented by having itself as a -parent. Due to the set-once design of the API, a parent-child relationship -cannot be modified once established. A child node can be any of the 8 node -types, but a parent node can only be one of the 3 container node types -(E57_STRUCTURE, E57_VECTOR, and E57_COMPRESSED_VECTOR). Each parent-child link -has a string name (the elementName) associated with it (See Node::elementName -for more details). More than one tree can be formed at any given time. Typically -small trees are temporarily constructed before attachment to an ImageFile so -that they will be written to the disk. - -@b Warning: user algorithms that use this function to walk the tree must take -care to handle the case where a node is its own parent (it is a root node). Use -Node::isRoot to avoid infinite loops or infinite recursion. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return A smart Node handle referencing the parent node or this node if is a -root node. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see Node::isRoot, Node::isAttached, CompressedVectorNode::CompressedVectorNode, Node::elementName -*/ -Node Node::parent() const -{ - return Node( impl_->parent() ); -} - -/*! -@brief Get absolute pathname of node. -@details -Nodes are organized into trees (acyclic graphs) by a parent-child relationship -between nodes. Each parent-child relationship has an associated elementName -string that is unique for a given parent. Any node in a given tree can be -identified by a sequence of elementNames of how to get to the node from the root -of the tree. An absolute pathname string that is formed by arranging this -sequence of elementNames separated by the "/" character with a leading "/" -prepended. - -Some example absolute pathNames: "/data3D/0/points/153/cartesianX", -"/data3D/0/points", -"/cameraImages/1/pose/rotation/w", and "/". These examples have probably been -attached to an ImageFile. Here is an example absolute pathName of a node in a -pose tree that has not yet been attached to an ImageFile: "/pose/rotation/w". - -A technical aside: the elementName of a root node does not appear in absolute -pathnames, since the "path" is between the staring node (the root) and the -ending node. By convention, in this API, a root node has the empty string ("") -as its elementName. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The absolute path name of the node. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see Node::elementName, Node::parent, Node::isRoot -*/ -ustring Node::pathName() const -{ - return impl_->pathName(); -} - -/*! -@brief Get element name of node. -@details -The elementName is a string associated with each parent-child link between -nodes. For a given parent, the elementName uniquely identifies each of its -children. Thus, any node in a tree can be identified by a sequence of -elementNames that form a path from the tree's root node (see Node::pathName for -more details). - -Three types of nodes (the container node types) can be parents: StructureNode, -VectorNode, and CompressedVectorNode. The children of a StructureNode are -explicitly given unique elementNames when they are attached to the parent (using -StructureNode::set). The children of VectorNode and CompressedVectorNode are -implicitly given elementNames based on their position in the list (starting at -"0"). In a CompressedVectorNode, the elementName can become quite large: -"1000000000" or more. However in a CompressedVectorNode, the elementName string -is not stored in the file and is deduced by the position of the child. - -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The element name of the node, or "" if a root node. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see Node::pathName, Node::parent, Node::isRoot -*/ -ustring Node::elementName() const -{ - return impl_->elementName(); -} - -/*! -@brief Get the ImageFile that was declared as the destination for the node -when it was created. -@details The first argument of the constructors of each of the 8 types of nodes -is an ImageFile that indicates which ImageFile the node will eventually be -attached to. This function returns that constructor argument. It is an error to -attempt to attach the node to a different ImageFile. However it is not an error -to not attach the node to any ImageFile (it's just wasteful). Use -Node::isAttached to check if the node actually did get attached. -@post No visible object state is modified. -@return The ImageFile that was declared as the destination for the node when it -was created. -@see Node::isAttached, -StructureNode::StructureNode(), VectorNode::VectorNode(), -CompressedVectorNode::CompressedVectorNode(), IntegerNode::IntegerNode(), -ScaledIntegerNode::ScaledIntegerNode(), FloatNode::FloatNode(), -StringNode::StringNode(), BlobNode::BlobNode() -*/ -ImageFile Node::destImageFile() const -{ - return ImageFile( impl_->destImageFile() ); -} - -/*! -@brief Has node been attached into the tree of an ImageFile. -@details Nodes are attached into an ImageFile tree by inserting them as children -(directly or indirectly) of the ImageFile's root node. Nodes can also be -attached to an ImageFile if they are used in the @c codecs or @c prototype trees -of an CompressedVectorNode that is attached. Attached nodes will be saved to -disk when the ImageFile is closed, and restored when the ImageFile is read back -in from disk. Unattached nodes will not be saved to disk. It is not recommended -to create nodes that are not eventually attached to the ImageFile. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible object state is modified. -@return @c true if node is child of (or in codecs or prototype of a child -CompressedVectorNode of) the root node of an ImageFile. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see Node::destImageFile, ImageFile::root -*/ -bool Node::isAttached() const -{ - return impl_->isAttached(); -} - -/*! -@brief Diagnostic function to print internal state of object to output stream -in an indented format. -@param [in] indent Number of spaces to indent all the printed lines of this -object. -@param [in] os Output stream to print on. -@details -All objects in the E57 Foundation API (with exception of E57Exception) support a -dump() function. These functions print out to the console a detailed listing of -the internal state of objects. The content of these printouts is not documented, -and is really of interest only to implementation developers/maintainers or the -really adventurous users. In implementations of the API other than the Reference -Implementation, the dump() functions may produce no output (although the -functions should still be defined). The output format may change from version to -version. -@post No visible object state is modified. -@throw No E57Exceptions -*/ -#ifdef E57_DEBUG -void Node::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void Node::dump( int indent, std::ostream &os ) const -{ -} -#endif - -/*! -@brief Test if two node handles refer to the same underlying node -@param [in] n2 The node to compare this node with -@post No visible object state is modified. -@return @c true if node handles refer to the same underlying node. -@throw No E57Exceptions -*/ -bool Node::operator==( Node n2 ) const -{ - return ( impl_ == n2.impl_ ); -} - -/*! -@brief Test if two node handles refer to different underlying nodes -@param [in] n2 The node to compare this node with -@post No visible object state is modified. -@return @c true if node handles refer to different underlying nodes. -@throw No E57Exceptions -*/ -bool Node::operator!=( Node n2 ) const -{ - return ( impl_ != n2.impl_ ); -} - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -Node::Node( NodeImplSharedPtr ni ) : impl_( ni ) -{ -} -//! @endcond - -//===================================================================================== -/*! -@class StructureNode -@brief An E57 element containing named child nodes. -@details -A StructureNode is a container of named child nodes, which may be any of the -eight node types. The children of a structure node must have unique -elementNames. Once a child node is set with a particular elementName, it may not -be modified. - -See Node class discussion for discussion of the common functions that -StructureNode supports. -@section structurenode_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin StructureNode::checkInvariant -@skip checkInvariant( -@until end StructureNode::checkInvariant - -@see Node -*/ - -/*! -@brief Create an empty StructureNode. -@param [in] destImageFile The ImageFile where the new node will eventually -be stored. -@details -A StructureNode is a container for collections of named E57 nodes. -The @a destImageFile indicates which ImageFile the StructureNode will eventually -be attached to. A node is attached to an ImageFile by adding it underneath the -predefined root of the ImageFile (gotten from ImageFile::root). It is not an -error to fail to attach the StructureNode to the @a destImageFile. It is an -error to attempt to attach the StructureNode to a different ImageFile. -@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be -true). -@pre The @a destImageFile must have been opened in write mode (i.e. -destImageFile.isWritable() must be true). -@return A smart StructureNode handle referencing the underlying object. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see Node -*/ -StructureNode::StructureNode( ImageFile destImageFile ) : impl_( new StructureNodeImpl( destImageFile.impl() ) ) -{ -} - -//! @brief Is this a root node. -//! @copydetails Node::isRoot() -bool StructureNode::isRoot() const -{ - return impl_->isRoot(); -} - -//! @brief Return parent of node, or self if a root node. -//! @copydetails Node::parent() -Node StructureNode::parent() const -{ - return Node( impl_->parent() ); -} - -//! @brief Get absolute pathname of node. -//! @copydetails Node::pathName() -ustring StructureNode::pathName() const -{ - return impl_->pathName(); -} - -//! @brief Get elementName string, that identifies the node in its parent. -//! @copydetails Node::elementName() -ustring StructureNode::elementName() const -{ - return impl_->elementName(); -} - -//! @brief Get the ImageFile that was declared as the destination for the node -//! when it was created. -//! @copydetails Node::destImageFile() -ImageFile StructureNode::destImageFile() const -{ - return ImageFile( impl_->destImageFile() ); -} - -//! @brief Has node been attached into the tree of an ImageFile. -//! @copydetails Node::isAttached() -bool StructureNode::isAttached() const -{ - return impl_->isAttached(); -} - -/*! -@brief Return number of child nodes contained by this StructureNode. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return Number of child nodes contained by this StructureNode. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see StructureNode::get(int64_t) const, -StructureNode::set, VectorNode::childCount -*/ -int64_t StructureNode::childCount() const -{ - return impl_->childCount(); -} - -/*! -@brief Is the given pathName defined relative to this node. -@param [in] pathName The absolute pathname, or pathname relative to this -object, to check. -@details -The @a pathName may be relative to this node, or absolute (starting with a "/"). -The origin of the absolute path name is the root of the tree that contains this -StructureNode. If this StructureNode is not attached to an ImageFile, the @a -pathName origin root will not the root node of an ImageFile. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return true if pathName is currently defined. -@throw ::E57_ERROR_BAD_PATH_NAME -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ImageFile::root, VectorNode::isDefined -*/ -bool StructureNode::isDefined( const ustring &pathName ) const -{ - return impl_->isDefined( pathName ); -} - -/*! -@brief Get a child element by positional index. -@param [in] index The index of child element to get, starting at 0. -@details -The order of children is not specified, and may be different than order the -children were added to the StructureNode. The order of children may change if -more children are added to the StructureNode. -@pre 0 <= @a index < childCount() -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return A smart Node handle referencing the child node. -@throw ::E57_ERROR_CHILD_INDEX_OUT_OF_BOUNDS -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see StructureNode::childCount, -StructureNode::get(const ustring&) const, VectorNode::get -*/ -Node StructureNode::get( int64_t index ) const -{ - return Node( impl_->get( index ) ); -} - -/*! -@brief Get a child by path name. -@param [in] pathName The absolute pathname, or pathname relative to this -object, of the object to get. The @a pathName may be relative to this node, or -absolute (starting with a "/"). The origin of the absolute path name is the root -of the tree that contains this StructureNode. If this StructureNode is not -attached to an ImageFile, the @a pathName origin root will not the root node of -an ImageFile. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@pre The @a pathName must be defined (i.e. isDefined(pathName)). -@post No visible state is modified. -@return A smart Node handle referencing the child node. -@throw ::E57_ERROR_BAD_PATH_NAME -@throw ::E57_ERROR_PATH_UNDEFINED -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see StructureNode::get(int64_t) const -*/ -Node StructureNode::get( const ustring &pathName ) const -{ - return Node( impl_->get( pathName ) ); -} - -/*! -@brief Add a new child at a given path - @param [in] pathName The absolute pathname, or pathname relative to this -object, that the child object @a n will be given. -@param [in] n The node to be added to the tree with given @a pathName. -@details -The @a pathName may be relative to this node, or absolute (starting with a "/"). -The origin of the absolute path name is the root of the tree that contains this -StructureNode. If this StructureNode is not attached to an ImageFile, the @a -pathName origin root will not the root node of an ImageFile. - -The path name formed from all element names in @a pathName except the last must -exist. If the @a pathName identifies the child of a VectorNode, then the last -element name in @a pathName must be numeric, and be equal to the childCount of -that VectorNode (the request is equivalent to VectorNode::append). The -StructureNode must not be a descendent of a homogeneous VectorNode with more -than one child. - -The element naming grammar specified by the ASTM E57 format standard are not -enforced in this function. This would be very difficult to do dynamically, as -some of the naming rules involve combinations of names. -@pre The new child node @a n must be a root node (i.e. n.isRoot()). -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@pre The associated destImageFile must have been opened in write mode (i.e. -destImageFile().isWritable()). -@pre The @a pathName must not already be defined (i.e. -!isDefined(pathName)). -@pre The associated destImageFile of this StructureNode and of @a n must be -same (i.e. destImageFile() == n.destImageFile()). -@post The @a pathName will be defined (i.e. isDefined(pathName)). -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_BAD_PATH_NAME -@throw ::E57_ERROR_PATH_UNDEFINED -@throw ::E57_ERROR_SET_TWICE -@throw ::E57_ERROR_ALREADY_HAS_PARENT -@throw ::E57_ERROR_DIFFERENT_DEST_IMAGEFILE -@throw ::E57_ERROR_HOMOGENEOUS_VIOLATION -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see VectorNode::append -*/ -void StructureNode::set( const ustring &pathName, const Node &n ) -{ - impl_->set( pathName, n.impl(), false ); -} - -//! @brief Diagnostic function to print internal state of object to output -//! stream in an indented format. -//! @copydetails Node::dump() -#ifdef E57_DEBUG -void StructureNode::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void StructureNode::dump( int indent, std::ostream &os ) const -{ -} -#endif - -/*! -@brief Upcast a StructureNode handle to a generic Node handle. -@details An upcast is always safe, and the compiler can automatically insert it -for initializations of Node variables and Node function arguments. -@return A smart Node handle referencing the underlying object. -@throw No E57Exceptions. -@see explanation in Node, Node::type(), StructureNode(const Node&) -*/ -StructureNode::operator Node() const -{ - /// Implicitly upcast from shared_ptr to SharedNodeImplPtr - /// and construct a Node object - return Node( impl_ ); -} - -/*! -@brief Downcast a generic Node handle to a StructureNode handle. -@param [in] n The generic handle to downcast. -@details The handle @a n must be for an underlying StructureNode, otherwise an -exception is thrown. In designs that need to avoid the exception, use -Node::type() to determine the actual type of the @a n before downcasting. This -function must be explicitly called (c++ compiler cannot insert it -automatically). -@return A smart StructureNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_NODE_DOWNCAST -@see Node::type(), StructureNode::operator Node() -*/ -StructureNode::StructureNode( const Node &n ) -{ - if ( n.type() != E57_STRUCTURE ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_NODE_DOWNCAST, "nodeType=" + toString( n.type() ) ); - } - - /// Set our shared_ptr to the downcast shared_ptr - impl_ = std::static_pointer_cast( n.impl() ); -} - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -StructureNode::StructureNode( std::weak_ptr fileParent ) : impl_( new StructureNodeImpl( fileParent ) ) -{ -} - -StructureNode::StructureNode( std::shared_ptr ni ) : impl_( ni ) -{ -} -//! @endcond - -//===================================================================================== -/*! -@class VectorNode -@brief An E57 element containing ordered vector of child nodes. -@details -A VectorNode is a container of ordered child nodes. -The child nodes are automatically assigned an elementName, which is a string -version of the positional index of the child starting at "0". Child nodes may -only be appended onto the end of a VectorNode. - -A VectorNode that is created with a restriction that its children must have the -same type is called a "homogeneous VectorNode". A VectorNode without such a -restriction is called a "heterogeneous VectorNode". - -See Node class discussion for discussion of the common functions that -StructureNode supports. -@section vectornode_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin VectorNode::checkInvariant -@skip checkInvariant( -@until end VectorNode::checkInvariant - -@see Node -*/ - -/*! -@brief Create a new empty Vector node. -@param [in] destImageFile The ImageFile where the new node will -eventually be stored. -@param [in] allowHeteroChildren Will child elements of differing types be -allowed in this VectorNode. -@details -A VectorNode is a ordered container of E57 nodes. -The @a destImageFile indicates which ImageFile the VectorNode will eventually be -attached to. A node is attached to an ImageFile by adding it underneath the -predefined root of the ImageFile (gotten from ImageFile::root). It is not an -error to fail to attach the VectorNode to the @a destImageFile. It is an error -to attempt to attach the VectorNode to a different ImageFile. - -If @a allowHeteroChildren is false, then the children that are appended to the -VectorNode must be identical in every visible characteristic except the stored -values. These visible characteristics include number of children (for -StructureNode and VectorNode descendents), number of records/prototypes/codecs -(for CompressedVectorNode), minimum/maximum attributes (for IntegerNode, -ScaledIntegerNode, FloatNode), byteCount (for BlobNode), scale/offset (for -ScaledIntegerNode), and all elementNames. The enforcement of this homogeneity -rule begins when the second child is appended to the VectorNode, thus it is not -an error to modify a child of a homogeneous VectorNode containing only one -child. - -If @a allowHeteroChildren is true, then the types of the children of the -VectorNode are completely unconstrained. -@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be -true). -@pre The @a destImageFile must have been opened in write mode (i.e. -destImageFile.isWritable() must be true). -@return A smart VectorNode handle referencing the underlying object. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see Node, VectorNode::allowHeteroChildren, ::E57_ERROR_HOMOGENEOUS_VIOLATION -*/ -VectorNode::VectorNode( ImageFile destImageFile, bool allowHeteroChildren ) : - impl_( new VectorNodeImpl( destImageFile.impl(), allowHeteroChildren ) ) -{ -} - -//! @brief Is this a root node. -//! @copydetails Node::isRoot() -bool VectorNode::isRoot() const -{ - return impl_->isRoot(); -} - -//! @brief Return parent of node, or self if a root node. -//! @copydetails Node::parent() -Node VectorNode::parent() const -{ - return Node( impl_->parent() ); -} - -//! @brief Get absolute pathname of node. -//! @copydetails Node::pathName() -ustring VectorNode::pathName() const -{ - return impl_->pathName(); -} - -//! @brief Get elementName string, that identifies the node in its parent.. -//! @copydetails Node::elementName() -ustring VectorNode::elementName() const -{ - return impl_->elementName(); -} - -//! @brief Get the ImageFile that was declared as the destination for the node -//! when it was created. -//! @copydetails Node::destImageFile() -ImageFile VectorNode::destImageFile() const -{ - return ImageFile( impl_->destImageFile() ); -} - -//! @brief Has node been attached into the tree of an ImageFile. -//! @copydetails Node::isAttached() -bool VectorNode::isAttached() const -{ - return impl_->isAttached(); -} - -/*! -@brief Get whether child elements are allowed to be different types? -@details -See the class discussion at bottom of VectorNode page for details of -homogeneous/heterogeneous VectorNode. The returned attribute is determined when -the VectorNode is created, and cannot be changed. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return True if child elements can be different types. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ::E57_ERROR_HOMOGENEOUS_VIOLATION -*/ -bool VectorNode::allowHeteroChildren() const -{ - return impl_->allowHeteroChildren(); -} - -/*! -@brief Get number of child elements in this VectorNode. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return Number of child elements in this VectorNode. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see VectorNode::get(int64_t), VectorNode::append, StructureNode::childCount -*/ -int64_t VectorNode::childCount() const -{ - return impl_->childCount(); -} - -/*! -@brief Is the given pathName defined relative to this node. -@param [in] pathName The absolute pathname, or pathname relative to this -object, to check. -@details -The @a pathName may be relative to this node, or absolute (starting with a "/"). -The origin of the absolute path name is the root of the tree that contains this -VectorNode. If this VectorNode is not attached to an ImageFile, the @a pathName -origin root will not the root node of an ImageFile. - -The element names of child elements of VectorNodes are numbers, encoded as -strings, starting at "0". -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return true if pathName is currently defined. -@throw ::E57_ERROR_BAD_PATH_NAME -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see StructureNode::isDefined -*/ -bool VectorNode::isDefined( const ustring &pathName ) const -{ - return impl_->isDefined( pathName ); -} - -/*! -@brief Get a child element by positional index. -@param [in] index The index of child element to get, starting at 0. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@pre 0 <= @a index < childCount() -@post No visible state is modified. -@return A smart Node handle referencing the child node. -@throw ::E57_ERROR_CHILD_INDEX_OUT_OF_BOUNDS -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see VectorNode::childCount, VectorNode::append, StructureNode::get(int64_t) const -*/ -Node VectorNode::get( int64_t index ) const -{ - return Node( impl_->get( index ) ); -} - -/*! -@brief Get a child element by string path name -@param [in] pathName The pathname, either absolute or relative, of the -object to get. -@details -The @a pathName may be relative to this node, or absolute (starting with a "/"). -The origin of the absolute path name is the root of the tree that contains this -VectorNode. If this VectorNode is not attached to an ImageFile, the @a pathName -origin root will not the root node of an ImageFile. - -The element names of child elements of VectorNodes are numbers, encoded as -strings, starting at "0". -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@pre The @a pathName must be defined (i.e. isDefined(pathName)). -@post No visible state is modified. -@return A smart Node handle referencing the child node. -@throw ::E57_ERROR_BAD_PATH_NAME -@throw ::E57_ERROR_PATH_UNDEFINED -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see VectorNode::childCount, VectorNode::append, StructureNode::get(int64_t) const -*/ -Node VectorNode::get( const ustring &pathName ) const -{ - return Node( impl_->get( pathName ) ); -} - -/*! -@brief Append a child element to end of VectorNode. -@param [in] n The node to be added as a child at end of the VectorNode. -@details -If the VectorNode is homogeneous and already has at least one child, then @a n -must be identical to the existing children in every visible characteristic -except the stored values. These visible characteristics include number of -children (for StructureNode and VectorNode descendents), number of -records/prototypes/codecs (for CompressedVectorNode), minimum/maximum attributes -(for IntegerNode, ScaledIntegerNode, FloatNode), byteCount (for BlobNode), -scale/offset (for ScaledIntegerNode), and all elementNames. - -The VectorNode must not be a descendent of a homogeneous VectorNode with more -than one child. -@pre The new child node @a n must be a root node (not already having a -parent). -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@pre The associated destImageFile must have been opened in write mode (i.e. -destImageFile().isWritable()). -@post the childCount is incremented. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_HOMOGENEOUS_VIOLATION -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_ALREADY_HAS_PARENT -@throw ::E57_ERROR_DIFFERENT_DEST_IMAGEFILE -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see VectorNode::childCount, VectorNode::get(int64_t), StructureNode::set -*/ -void VectorNode::append( const Node &n ) -{ - impl_->append( n.impl() ); -} - -//! @brief Diagnostic function to print internal state of object to output -//! stream in an indented format. -//! @copydetails Node::dump() -#ifdef E57_DEBUG -void VectorNode::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void VectorNode::dump( int indent, std::ostream &os ) const -{ -} -#endif - -/*! -@brief Upcast a VectorNode handle to a generic Node handle. -@details An upcast is always safe, and the compiler can automatically insert it -for initializations of Node variables and Node function arguments. -@return A smart Node handle referencing the underlying object. -@throw No E57Exceptions. -@see explanation in Node, Node::type(), VectorNode(const Node&) -*/ -VectorNode::operator Node() const -{ - /// Implicitly upcast from shared_ptr to SharedNodeImplPtr - /// and construct a Node object - return Node( impl_ ); -} - -/*! -@brief Downcast a generic Node handle to a VectorNode handle. -@param [in] n The generic handle to downcast. -@details The handle @a n must be for an underlying VectorNode, otherwise an -exception is thrown. In designs that need to avoid the exception, use -Node::type() to determine the actual type of the @a n before downcasting. This -function must be explicitly called (c++ compiler cannot insert it -automatically). -@return A smart VectorNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_NODE_DOWNCAST -@see Node::type(), VectorNode::operator Node() -*/ -VectorNode::VectorNode( const Node &n ) -{ - if ( n.type() != E57_VECTOR ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_NODE_DOWNCAST, "nodeType=" + toString( n.type() ) ); - } - - /// Set our shared_ptr to the downcast shared_ptr - impl_ = std::static_pointer_cast( n.impl() ); -} - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -VectorNode::VectorNode( std::shared_ptr ni ) : impl_( ni ) -{ -} -//! @endcond - -//===================================================================================== -/*! -@class SourceDestBuffer -@brief A memory buffer to transfer data to/from a CompressedVectorNode in a -block. -@details -The SourceDestBuffer is an encapsulation of a buffer in memory that will -transfer data to/from a field in a CompressedVectorNode. The API user is -responsible for creating the actual memory buffer, describing it correctly to -the API, making sure it exists during the transfer period, and destroying it -after the transfer is complete. Additionally, the SourceDestBuffer has -information that specifies the connection to the CompressedVectorNode field -(i.e. the field's path name in the prototype). - -The type of buffer element may be an assortment of built-in C++ memory types. -There are all combinations of signed/unsigned and 8/16/32/64 bit integers -(except unsigned 64bit integer, which is not supported in the ASTM standard), -bool, float, double, as well as a vector of variable length unicode strings. The -compiler selects the appropriate constructor automatically based on the type of -the buffer array. However, the API user is responsible for reporting the correct -length and stride options (otherwise unspecified behavior can occur). - -The connection of the SourceDestBuffer to a CompressedVectorNode field is -established by specifying the pathName. There are several options to this -connection: doConversion and doScaling, which are described in the constructor -documentation. - -@section sourcedestbuffer_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin SourceDestBuffer::checkInvariant -@skip checkInvariant( -@until end SourceDestBuffer::checkInvariant - -@see Node -*/ - -/*! -@brief Designate buffers to transfer data to/from a CompressedVectorNode in a -block. -@param [in] destImageFile The ImageFile where the new node will eventually be -stored. -@param [in] pathName The pathname of the field in CompressedVectorNode -that will transfer data to/from. -@param [in] b The caller allocated memory buffer. -@param [in] capacity The total number of memory elements in buffer @a b. -@param [in] doConversion Will a conversion be attempted between memory and -ImageFile representations. -@param [in] doScaling In a ScaledInteger field, do memory elements hold -scaled values, if false they hold raw values. -@param [in] stride The number of bytes between memory elements. If -zero, defaults to sizeof memory element. -@details -This overloaded form of the SourceDestBuffer constructor declares a buffer @a b -to be the source/destination of a transfer of values stored in a -CompressedVectorNode.\n\n - -The @a pathName will be used to identify a Node in the prototype that will -get/receive data from this buffer. The @a pathName may be an absolute path name -(e.g. "/cartesianX") or a path name relative to the root of the prototype (i.e. -the absolute path name without the leading "/", for example: "cartesianX").\n\n - -The type of @a b is used to determine the MemoryRepresentation of the -SourceDestBuffer. The buffer @a b may be used for multiple block transfers. See -discussions of operation of SourceDestBuffer attributes in -SourceDestBuffer::memoryRepresentation, SourceDestBuffer::capacity, -SourceDestBuffer::doConversion, and SourceDestBuffer::doScaling, and -SourceDestBuffer::stride.\n\n - -The API user is responsible for ensuring that the lifetime of the @a b memory -buffer exceeds the time that it is used in transfers (i.e. the E57 Foundation -Implementation cannot detect that the buffer been destroyed).\n\n - -The @a capacity must match the capacity of all other SourceDestBuffers that will -participate in a transfer with a CompressedVectorNode. - -@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be -true). -@pre The stride must be >= sizeof(*b) -@return A smart SourceDestBuffer handle referencing the underlying object. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_BAD_PATH_NAME -@throw ::E57_ERROR_BAD_BUFFER -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ImageFile::reader, ImageFile::writer, -CompressedVectorReader::read(std::vector&), -CompressedVectorWriter::write(std::vector&) -*/ -SourceDestBuffer::SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, int8_t *b, const size_t capacity, - bool doConversion, bool doScaling, size_t stride ) : - impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, doScaling ) ) -{ - impl_->setTypeInfo( b, stride ); -} - -//! @brief Designate buffers to transfer data to/from a CompressedVectorNode -//! in a block. -//! @copydetails SourceDestBuffer::SourceDestBuffer(ImageFile,const -//! ustring,int8_t*,size_t,bool,bool,size_t) -SourceDestBuffer::SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, uint8_t *b, const size_t capacity, - bool doConversion, bool doScaling, size_t stride ) : - impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, doScaling ) ) -{ - impl_->setTypeInfo( b, stride ); -} - -//! @brief Designate buffers to transfer data to/from a CompressedVectorNode -//! in a block. -//! @copydetails SourceDestBuffer::SourceDestBuffer(ImageFile,const -//! ustring,int8_t*,size_t,bool,bool,size_t) -SourceDestBuffer::SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, int16_t *b, const size_t capacity, - bool doConversion, bool doScaling, size_t stride ) : - impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, doScaling ) ) -{ - impl_->setTypeInfo( b, stride ); -} - -//! @brief Designate buffers to transfer data to/from a CompressedVectorNode -//! in a block. -//! @copydetails SourceDestBuffer::SourceDestBuffer(ImageFile,const -//! ustring,int8_t*,size_t,bool,bool,size_t) -SourceDestBuffer::SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, uint16_t *b, - const size_t capacity, bool doConversion, bool doScaling, size_t stride ) : - impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, doScaling ) ) -{ - impl_->setTypeInfo( b, stride ); -} - -//! @brief Designate buffers to transfer data to/from a CompressedVectorNode -//! in a block. -//! @copydetails SourceDestBuffer::SourceDestBuffer(ImageFile,const -//! ustring,int8_t*,size_t,bool,bool,size_t) -SourceDestBuffer::SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, int32_t *b, const size_t capacity, - bool doConversion, bool doScaling, size_t stride ) : - impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, doScaling ) ) -{ - impl_->setTypeInfo( b, stride ); -} - -//! @brief Designate buffers to transfer data to/from a CompressedVectorNode -//! in a block. -//! @copydetails SourceDestBuffer::SourceDestBuffer(ImageFile,const -//! ustring,int8_t*,size_t,bool,bool,size_t) -SourceDestBuffer::SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, uint32_t *b, - const size_t capacity, bool doConversion, bool doScaling, size_t stride ) : - impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, doScaling ) ) -{ - impl_->setTypeInfo( b, stride ); -} - -//! @brief Designate buffers to transfer data to/from a CompressedVectorNode -//! in a block. -//! @copydetails SourceDestBuffer::SourceDestBuffer(ImageFile,const -//! ustring,int8_t*,size_t,bool,bool,size_t) -SourceDestBuffer::SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, int64_t *b, const size_t capacity, - bool doConversion, bool doScaling, size_t stride ) : - impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, doScaling ) ) -{ - impl_->setTypeInfo( b, stride ); -} - -//! @brief Designate buffers to transfer data to/from a CompressedVectorNode -//! in a block. -//! @copydetails SourceDestBuffer::SourceDestBuffer(ImageFile,const -//! ustring,int8_t*,size_t,bool,bool,size_t) -SourceDestBuffer::SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, bool *b, const size_t capacity, - bool doConversion, bool doScaling, size_t stride ) : - impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, doScaling ) ) -{ - impl_->setTypeInfo( b, stride ); -} - -//! @brief Designate buffers to transfer data to/from a CompressedVectorNode -//! in a block. -//! @copydetails SourceDestBuffer::SourceDestBuffer(ImageFile,const -//! ustring,int8_t*,size_t,bool,bool,size_t) -SourceDestBuffer::SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, float *b, const size_t capacity, - bool doConversion, bool doScaling, size_t stride ) : - impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, doScaling ) ) -{ - impl_->setTypeInfo( b, stride ); -} - -//! @brief Designate buffers to transfer data to/from a CompressedVectorNode -//! in a block. -//! @copydetails SourceDestBuffer::SourceDestBuffer(ImageFile,const -//! ustring,int8_t*,size_t,bool,bool,size_t) -SourceDestBuffer::SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, double *b, const size_t capacity, - bool doConversion, bool doScaling, size_t stride ) : - impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, doScaling ) ) -{ - impl_->setTypeInfo( b, stride ); -} - -/*! -@brief Designate vector of strings to transfer data to/from a CompressedVector -as a block. -@param [in] destImageFile The ImageFile where the new node will eventually be -stored. -@param [in] pathName The pathname of the field in CompressedVectorNode -that will transfer data to/from. -@param [in] b The caller created vector of ustrings to transfer -from/to. -@details -This overloaded form of the SourceDestBuffer constructor declares a -vector to be the source/destination of a transfer of StringNode values -stored in a CompressedVectorNode. - -The @a pathName will be used to identify a Node in the prototype that will -get/receive data from this buffer. The @a pathName may be an absolute path name -(e.g. "/cartesianX") or a path name relative to the root of the prototype (i.e. -the absolute path name without the leading "/", for example: "cartesianX"). - -The @a b->size() must match capacity of all other SourceDestBuffers that will -participate in a transfer with a CompressedVectorNode (string or any other type -of buffer). In a read into the SourceDestBuffer, the previous contents of the -strings in the vector are lost, and the memory space is potentially freed. The -@a b->size() of the vector will not be changed. It is an error to request a -read/write of more records that @a b->size() (just as it would be for buffers of -integer types). The API user is responsible for ensuring that the lifetime of -the @a b vector exceeds the time that it is used in transfers (i.e. the E57 -Foundation Implementation cannot detect that the buffer been destroyed). - -@pre b.size() must be > 0. -@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be -true). -@return A smart SourceDestBuffer handle referencing the underlying object. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_BAD_PATH_NAME -@throw ::E57_ERROR_BAD_BUFFER -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see SourceDestBuffer::doConversion for discussion on representations compatible with string SourceDestBuffers. -*/ -SourceDestBuffer::SourceDestBuffer( ImageFile destImageFile, const ustring &pathName, StringList *b ) : - impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, b ) ) -{ -} - -/*! -@brief Get path name in prototype that this SourceDestBuffer will transfer -data to/from. -@details -The prototype of a CompressedVectorNode describes the fields that are in each -record. This function returns the path name of the node in the prototype tree -that this SourceDestBuffer will write/read. The correctness of this path name is -checked when this SourceDestBuffer is associated with a CompressedVectorNode -(either in CompressedVectorNode::writer, -CompressedVectorWriter::write(std::vector&, unsigned), -CompressedVectorNode::reader, -CompressedVectorReader::read(std::vector&)). - -@post No visible state is modified. -@return Path name in prototype that this SourceDestBuffer will transfer data -to/from. -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVector, CompressedVectorNode::prototype -*/ -ustring SourceDestBuffer::pathName() const -{ - return impl_->pathName(); -} - -/*! -@brief Get memory representation of the elements in this SourceDestBuffer. -@details -The memory representation is deduced from which overloaded SourceDestBuffer -constructor was used. The memory representation is independent of the type and -minimum/maximum bounds of the node in the prototype that the SourceDestBuffer -will transfer to/from. However, some combinations will result in an error if -doConversion is not requested (e.g. E57_INT16 and FloatNode). - -Some combinations risk an error occurring during a write, if a value is too -large (e.g. writing a E57_INT16 memory representation to an IntegerNode with -minimum=-1024 maximum=1023). Some combinations risk an error occurring during a -read, if a value is too large (e.g. reading an IntegerNode with minimum=-1024 -maximum=1023 int an E57_INT8 memory representation). Some combinations are never -possible (e.g. E57_INT16 and StringNode). -@post No visible state is modified. -@return Memory representation of the elements in buffer. -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see MemoryRepresentation, NodeType -*/ -MemoryRepresentation SourceDestBuffer::memoryRepresentation() const -{ - return impl_->memoryRepresentation(); -} - -/*! -@brief Get total capacity of buffer. -@details -The API programmer is responsible for correctly specifying the length of a -buffer. This function returns that declared length. If the length is incorrect -(in particular, too long) memory may be corrupted or erroneous values written. -@post No visible state is modified. -@return Total capacity of buffer. -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -*/ -size_t SourceDestBuffer::capacity() const -{ - return impl_->capacity(); -} - -/*! -@brief Get whether conversions will be performed to match the memory type of -buffer. -@details -The API user must explicitly request conversion between basic representation -groups in memory and on the disk. The four basic representation groups are: -integer, boolean, floating point, and string. There is no distinction between -integer and boolean groups on the disk (they both use IntegerNode). A explicit -request for conversion between single and double precision floating point -representations is not required. - -The most useful conversion is between integer and floating point representation -groups. Conversion from integer to floating point representations cannot result -in an overflow, and is usually loss-less (except for extremely large integers). -Conversion from floating point to integer representations can result in an -overflow, and can be lossy. - -Conversion between any of the integer, boolean, and floating point -representation groups is supported. No conversion from the string to any other -representation group is possible. Missing or unsupported conversions are -detected when the first transfer is attempted (i.e. not when the -CompressedVectorReader or CompressedVectorWriter is created). - -@post No visible state is modified. -@return true if conversions will be performed to match the memory type of -buffer. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -*/ -bool SourceDestBuffer::doConversion() const -{ - return impl_->doConversion(); -} - -/*! -@brief Get whether scaling will be performed for ScaledIntegerNode transfers. -@details -The doScaling option only applies to ScaledIntegerNodes stored in a -CompressedVectorNode on the disk (it is ignored if a ScaledIntegerNode is not -involved). - -As a convenience, an E57 Foundation Implementation can perform scaling of data -so that the API user can manipulate scaledValues rather than rawValues. For a -reader, the scaling process is: scaledValue = (rawValue * scale) + offset. For a -writer, the scaling process is reversed: rawValue = (scaledValue - offset) / -scale. The result performing a scaling in a reader (or "unscaling" in a writer) -is always a floating point number. This floating point number may have to be -converted to be compatible with the destination representation. If the -destination representation is not floating point, there is a risk of violating -declared min/max bounds. Because of this risk, it is recommended that scaling -only be requested for reading scaledValues from ScaledIntegerNodes into floating -point numbers in memory. - -It is also possible (and perhaps safest of all) to never request that scaling be -performed, and always deal with rawValues outside the API. Note this does not -mean that ScaledIntegerNodes should be avoided. ScaledIntgerNodes are essential -for encoding numeric data with fractional parts in CompressedVectorNodes. -Because the ASTM E57 format recommends that SI units without prefix be used -(i.e. meters, not milli-meters or micro-furlongs), almost every measured value -will have a fractional part. - -@post No visible state is modified. -@return true if scaling will be performed for ScaledInteger transfers. -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ScaledIntegerNode -*/ -bool SourceDestBuffer::doScaling() const -{ - return impl_->doScaling(); -} - -/*! -@brief Get number of bytes between consecutive memory elements in buffer -@details -Elements in a memory buffer do not have to be consecutive. -They can also be spaced at regular intervals. -This allows a value to be picked out of an array of C++ structures (the stride -would be the size of the structure). In the case that the element values are -stored consecutively in memory, the stride equals the size of the memory -representation of the element. -@post No visible state is modified. -@return Number of bytes between consecutive memory elements in buffer -*/ -size_t SourceDestBuffer::stride() const -{ - return impl_->stride(); -} - -//! @brief Diagnostic function to print internal state of object to output -//! stream in an indented format. -//! @copydetails Node::dump() -#ifdef E57_DEBUG -void SourceDestBuffer::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void SourceDestBuffer::dump( int indent, std::ostream &os ) const -{ -} -#endif - -//===================================================================================== -/*! -@class CompressedVectorReader -@brief An iterator object keeping track of a read in progress from a -CompressedVectorNode. -@details -A CompressedVectorReader object is a block iterator that reads blocks of records -from a CompressedVectorNode and stores them in memory buffers -(SourceDestBuffers). Blocks of records are processed rather than a single -record-at-a-time for efficiency reasons. The CompressedVectorReader class -encapsulates all the state that must be saved in between the processing of one -record block and the next (e.g. partially read disk pages, or data decompression -state). New memory buffers can be used for each record block read, or the -previous buffers can be reused. - -CompressedVectorReader objects have an open/closed state. -Initially a newly created CompressedVectorReader is in the open state. -After the API user calls CompressedVectorReader::close, the object will be in -the closed state and no more data transfers will be possible. - -There is no CompressedVectorReader constructor in the API. -The function CompressedVectorNode::reader returns an already constructed -CompressedVectorReader object with given memory buffers (SourceDestBuffers) -already associated. - -It is recommended to call CompressedVectorReader::close to gracefully end the -transfer. Unlike the CompressedVectorWriter, not all fields in the record of the -CompressedVectorNode are required to be read at one time. - -@section CompressedVectorReader_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin CompressedVectorReader::checkInvariant -@skip checkInvariant( -@until end CompressedVectorReader::checkInvariant - -@see CompressedVectorNode, CompressedVectorWriter -*/ - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -CompressedVectorReader::CompressedVectorReader( std::shared_ptr ni ) : impl_( ni ) -{ -} -//! @endcond - -/*! -@brief Request transfer of blocks of data from CompressedVectorNode into -previously designated destination buffers. -@details -The SourceDestBuffers used are previously designated either in -CompressedVectorNode::reader where this object was created, or in the last call -to CompressedVectorReader::read(std::vector&) where new -buffers were designated. The function will always return the full number of -records requested (the capacity of the SourceDestBuffers) unless it has reached -the end of the CompressedVectorNode, in which case it will return less than the -capacity of the SourceDestBuffers. Partial reads will store the records at the -beginning of the SourceDestBuffers. It is not an error to call this function -after all records in the CompressedVectorNode have been read (the function -returns 0). - -If a conversion or bounds error occurs during the transfer, the -CompressedVectorReader is left in an undocumented state (it can't be used any -further). If a file I/O or checksum error occurs during the transfer, both the -CompressedVectorReader and the associated ImageFile are left in an undocumented -state (they can't be used any further). - -The API user is responsible for ensuring that the underlying memory buffers -represented in the SourceDestBuffers still exist when this function is called. -The E57 Foundation Implementation cannot detect that a memory buffer been -destroyed. - -@pre The associated ImageFile must be open. -@pre This CompressedVectorReader must be open (i.e isOpen()) -@return The number of records read. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_READER_NOT_OPEN -@throw ::E57_ERROR_CONVERSION_REQUIRED This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_VALUE_NOT_REPRESENTABLE This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_REAL64_TOO_LARGE This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_EXPECTING_NUMERIC This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_EXPECTING_USTRING This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_BAD_CV_PACKET This CompressedVectorReader, associated -ImageFile in undocumented state -@throw ::E57_ERROR_LSEEK_FAILED This CompressedVectorReader, associated -ImageFile in undocumented state -@throw ::E57_ERROR_READ_FAILED This CompressedVectorReader, associated -ImageFile in undocumented state -@throw ::E57_ERROR_BAD_CHECKSUM This CompressedVectorReader, associated -ImageFile in undocumented state -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorReader::read(std::vector&), -CompressedVectorNode::reader, SourceDestBuffer, -CompressedVectorReader::read(std::vector&) -*/ -unsigned CompressedVectorReader::read() -{ - return impl_->read(); -} - -/*! -@brief Request transfer of block of data from CompressedVectorNode into given -destination buffers. -@param [in] dbufs Vector of memory buffers that will receive data read -from a CompressedVectorNode. -@details -The @a dbufs must all have the same capacity. -The specified @a dbufs must have same number of elements as previously -designated SourceDestBuffer vector. The each SourceDestBuffer within @a dbufs -must be identical to the previously designated SourceDestBuffer except for -capacity and buffer address. - -The @a dbufs locations are saved so that a later call to -CompressedVectorReader::read() can be used without having to re-specify the -SourceDestBuffers. - -The function will always return the full number of records requested (the -capacity of the SourceDestBuffers) unless it has reached the end of the -CompressedVectorNode, in which case it will return less than the capacity of the -SourceDestBuffers. Partial reads will store the records at the beginning of the -SourceDestBuffers. It is not an error to call this function after all records in -the CompressedVectorNode have been read (the function returns 0). - -If a conversion or bounds error occurs during the transfer, the -CompressedVectorReader is left in an undocumented state (it can't be used any -further). If a file I/O or checksum error occurs during the transfer, both the -CompressedVectorReader and the associated ImageFile are left in an undocumented -state (they can't be used any further). - -The API user is responsible for ensuring that the underlying memory buffers -represented in the SourceDestBuffers still exist when this function is called. -The E57 Foundation Implementation cannot detect that a memory buffer been -destroyed. - -@pre The associated ImageFile must be open. -@pre This CompressedVectorReader must be open (i.e isOpen()) -@return The number of records read. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_READER_NOT_OPEN -@throw ::E57_ERROR_PATH_UNDEFINED -@throw ::E57_ERROR_BUFFER_SIZE_MISMATCH -@throw ::E57_ERROR_BUFFER_DUPLICATE_PATHNAME -@throw ::E57_ERROR_CONVERSION_REQUIRED This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_VALUE_NOT_REPRESENTABLE This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_REAL64_TOO_LARGE This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_EXPECTING_NUMERIC This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_EXPECTING_USTRING This CompressedVectorReader -in undocumented state -@throw ::E57_ERROR_BAD_CV_PACKET This CompressedVectorReader, associated -ImageFile in undocumented state -@throw ::E57_ERROR_LSEEK_FAILED This CompressedVectorReader, associated -ImageFile in undocumented state -@throw ::E57_ERROR_READ_FAILED This CompressedVectorReader, associated -ImageFile in undocumented state -@throw ::E57_ERROR_BAD_CHECKSUM This CompressedVectorReader, associated -ImageFile in undocumented state -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorReader::read(), CompressedVectorNode::reader, SourceDestBuffer -*/ -unsigned CompressedVectorReader::read( std::vector &dbufs ) -{ - return impl_->read( dbufs ); -} - -/*! -@brief Set record number of CompressedVectorNode where next read will start. -@param [in] recordNumber The index of record in ComressedVectorNode where -next read using this CompressedVectorReader will start. -@details -This function may be called at any time (as long as ImageFile and -CompressedVectorReader are open). The next read will start at the given -recordNumber. It is not an error to seek to recordNumber = childCount() (i.e. to -one record past end of CompressedVectorNode). - -@pre @a recordNumber <= childCount() of CompressedVectorNode. -@pre The associated ImageFile must be open. -@pre This CompressedVectorReader must be open (i.e isOpen()) -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_READER_NOT_OPEN -@throw ::E57_ERROR_BAD_CV_PACKET -@throw ::E57_ERROR_LSEEK_FAILED -@throw ::E57_ERROR_READ_FAILED -@throw ::E57_ERROR_BAD_CHECKSUM -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorNode::reader -*/ -void CompressedVectorReader::seek( int64_t recordNumber ) -{ - impl_->seek( recordNumber ); -} - -/*! -@brief End the read operation. -@details -It is recommended that this function be called to gracefully end a transfer to a -CompressedVectorNode. It is not an error to call this function if the -CompressedVectorReader is already closed. This function will cause the -CompressedVectorReader to enter the closed state, and any further transfers -requests will fail. - -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorReader::isOpen, CompressedVectorNode::reader -*/ -void CompressedVectorReader::close() -{ - impl_->close(); -} - -/*! -@brief Test whether CompressedVectorReader is still open for reading. -@pre The associated ImageFile must be open. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorReader::close, CompressedVectorNode::reader -*/ -bool CompressedVectorReader::isOpen() -{ - return impl_->isOpen(); -} - -/*! -@brief Return the CompressedVectorNode being read. -@details -It is not an error if this CompressedVectorReader is closed. -@pre The associated ImageFile must be open. -@return A smart CompressedVectorNode handle referencing the underlying object -being read from. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorReader::close, CompressedVectorNode::reader -*/ -CompressedVectorNode CompressedVectorReader::compressedVectorNode() const -{ - return impl_->compressedVectorNode(); -} - -//! @brief Diagnostic function to print internal state of object to output -//! stream in an indented format. -//! @copydetails Node::dump() -#ifdef E57_DEBUG -void CompressedVectorReader::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void CompressedVectorReader::dump( int indent, std::ostream &os ) const -{ -} -#endif - -//===================================================================================== -/*! -@class CompressedVectorWriter -@brief An iterator object keeping track of a write in progress to a -CompressedVectorNode. -@details -A CompressedVectorWriter object is a block iterator that reads blocks of records -from memory and stores them in a CompressedVectorNode. Blocks of records are -processed rather than a single record-at-a-time for efficiency reasons. The -CompressedVectorWriter class encapsulates all the state that must be saved in -between the processing of one record block and the next (e.g. partially written -disk pages, partially filled bytes in a bytestream, or data compression state). -New memory buffers can be used for each record block write, or the previous -buffers can be reused. - -CompressedVectorWriter objects have an open/closed state. -Initially a newly created CompressedVectorWriter is in the open state. -After the API user calls CompressedVectorWriter::close, the object will be in -the closed state and no more data transfers will be possible. - -There is no CompressedVectorWriter constructor in the API. -The function CompressedVectorNode::writer returns an already constructed -CompressedVectorWriter object with given memory buffers (SourceDestBuffers) -already associated. CompressedVectorWriter::close must explicitly be called to -safely and gracefully end the transfer. - -@b Warning: If CompressedVectorWriter::close is not called before the -CompressedVectorWriter destructor is invoked, all writes to the -CompressedVectorNode will be lost (it will have zero children). - -@section CompressedVectorWriter_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin CompressedVectorWriter::checkInvariant -@skip checkInvariant( -@until end CompressedVectorWriter::checkInvariant - -@see CompressedVectorNode, CompressedVectorReader -*/ - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -CompressedVectorWriter::CompressedVectorWriter( std::shared_ptr ni ) : impl_( ni ) -{ -} -//! @endcond - -/*! -@brief Request transfer of blocks of data to CompressedVectorNode from -previously designated source buffers. -@param [in] recordCount Number of records to write. -@details -The SourceDestBuffers used are previously designated either in -CompressedVectorNode::writer where this object was created, or in the last call -to CompressedVectorWriter::write(std::vector&, unsigned) where -new buffers were designated. - -If a conversion or bounds error occurs during the transfer, the -CompressedVectorWriter is left in an undocumented state (it can't be used any -further), and all previously written records are deleted from the associated -CompressedVectorNode which will then have zero children. If a file I/O or -checksum error occurs during the transfer, both this CompressedVectorWriter and -the associated ImageFile are left in an undocumented state (they can't be used -any further). If CompressedVectorWriter::close is not called before the -CompressedVectorWriter destructor is invoked, all writes to the -CompressedVectorNode will be lost (it will have zero children). - -@pre The associated ImageFile must be open. -@pre This CompressedVectorWriter must be open (i.e isOpen()) -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_WRITER_NOT_OPEN -@throw ::E57_ERROR_PATH_UNDEFINED -@throw ::E57_ERROR_NO_BUFFER_FOR_ELEMENT -@throw ::E57_ERROR_BUFFER_SIZE_MISMATCH -@throw ::E57_ERROR_BUFFER_DUPLICATE_PATHNAME -@throw ::E57_ERROR_CONVERSION_REQUIRED This CompressedVectorWriter in -undocumented state, associated CompressedVectorNode modified but consistent, -associated ImageFile modified but consistent. -@throw ::E57_ERROR_VALUE_OUT_OF_BOUNDS This CompressedVectorWriter in -undocumented state, associated CompressedVectorNode modified but consistent, -associated ImageFile modified but consistent. -@throw ::E57_ERROR_VALUE_NOT_REPRESENTABLE This CompressedVectorWriter in -undocumented state, associated CompressedVectorNode modified but consistent, -associated ImageFile modified but consistent. -@throw ::E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE This CompressedVectorWriter -in undocumented state, associated CompressedVectorNode modified but consistent, -associated ImageFile modified but consistent. -@throw ::E57_ERROR_REAL64_TOO_LARGE This CompressedVectorWriter in -undocumented state, associated CompressedVectorNode modified but consistent, -associated ImageFile modified but consistent. -@throw ::E57_ERROR_EXPECTING_NUMERIC This CompressedVectorWriter in -undocumented state, associated CompressedVectorNode modified but consistent, -associated ImageFile modified but consistent. -@throw ::E57_ERROR_EXPECTING_USTRING This CompressedVectorWriter in -undocumented state, associated CompressedVectorNode modified but consistent, -associated ImageFile modified but consistent. -@throw ::E57_ERROR_LSEEK_FAILED This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_READ_FAILED This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_WRITE_FAILED This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_BAD_CHECKSUM This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorWriter::write(std::vector&,unsigned), -CompressedVectorNode::writer, CompressedVectorWriter::close, SourceDestBuffer, -E57Exception -*/ -void CompressedVectorWriter::write( const size_t recordCount ) -{ - impl_->write( recordCount ); -} - -/*! -@brief Request transfer of block of data to CompressedVectorNode from given -source buffers. -@param [in] sbufs Vector of memory buffers that hold data to be -written to a CompressedVectorNode. -@param [in] recordCount Number of records to write. -@details -The @a sbufs must all have the same capacity. -The @a sbufs capacity must be >= @a recordCount. -The specified @a sbufs must have same number of elements as previously -designated SourceDestBuffer vector. The each SourceDestBuffer within @a sbufs -must be identical to the previously designated SourceDestBuffer except for -capacity and buffer address. - -The @a sbufs locations are saved so that a later call to -CompressedVectorWriter::write(unsigned) can be used without having to re-specify -the SourceDestBuffers. - -If a conversion or bounds error occurs during the transfer, the -CompressedVectorWriter is left in an undocumented state (it can't be used any -further), and all previously written records are deleted from the the associated -CompressedVectorNode which will then have zero children. If a file I/O or -checksum error occurs during the transfer, both this CompressedVectorWriter and -the associated ImageFile are left in an undocumented state (they can't be used -any further). - -@b Warning: If CompressedVectorWriter::close is not called before the -CompressedVectorWriter destructor is invoked, all writes to the -CompressedVectorNode will be lost (it will have zero children). - -@pre The associated ImageFile must be open. -@pre This CompressedVectorWriter must be open (i.e isOpen()) -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_WRITER_NOT_OPEN -@throw ::E57_ERROR_PATH_UNDEFINED -@throw ::E57_ERROR_NO_BUFFER_FOR_ELEMENT -@throw ::E57_ERROR_BUFFER_SIZE_MISMATCH -@throw ::E57_ERROR_BUFFER_DUPLICATE_PATHNAME -@throw ::E57_ERROR_CONVERSION_REQUIRED This CompressedVectorWriter in -undocumented state, associated ImageFile modified but consistent. -@throw ::E57_ERROR_VALUE_OUT_OF_BOUNDS This CompressedVectorWriter in -undocumented state, associated ImageFile modified but consistent. -@throw ::E57_ERROR_VALUE_NOT_REPRESENTABLE This CompressedVectorWriter in -undocumented state, associated ImageFile modified but consistent. -@throw ::E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE This CompressedVectorWriter -in undocumented state, associated ImageFile modified but consistent. -@throw ::E57_ERROR_REAL64_TOO_LARGE This CompressedVectorWriter in -undocumented state, associated ImageFile modified but consistent. -@throw ::E57_ERROR_EXPECTING_NUMERIC This CompressedVectorWriter in -undocumented state, associated ImageFile modified but consistent. -@throw ::E57_ERROR_EXPECTING_USTRING This CompressedVectorWriter in -undocumented state, associated ImageFile modified but consistent. -@throw ::E57_ERROR_LSEEK_FAILED This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_READ_FAILED This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_WRITE_FAILED This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_BAD_CHECKSUM This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorWriter::write(unsigned), CompressedVectorNode::writer, -CompressedVectorWriter::close, SourceDestBuffer, E57Exception -*/ -void CompressedVectorWriter::write( std::vector &sbufs, const size_t recordCount ) -{ - impl_->write( sbufs, recordCount ); -} - -/*! -@brief End the write operation. -@details -This function must be called to safely and gracefully end a transfer to a -CompressedVectorNode. This is required because errors cannot be communicated -from the CompressedVectorNode destructor (in C++ destructors can't throw -exceptions). It is not an error to call this function if the -CompressedVectorWriter is already closed. This function will cause the -CompressedVectorWriter to enter the closed state, and any further transfers -requests will fail. - -@b Warning: If this function is not called before the CompressedVectorWriter -destructor is invoked, all writes to the CompressedVectorNode will be lost (it -will have zero children). -@pre The associated ImageFile must be open. -@post This CompressedVectorWriter is closed (i.e !isOpen()) -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_LSEEK_FAILED This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_READ_FAILED This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_WRITE_FAILED This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_BAD_CHECKSUM This CompressedVectorWriter, associated -ImageFile in undocumented state -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorWriter::isOpen -*/ -void CompressedVectorWriter::close() -{ - impl_->close(); -} - -/*! -@brief Test whether CompressedVectorWriter is still open for writing. -@pre The associated ImageFile must be open. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorWriter::close, CompressedVectorNode::writer -*/ -bool CompressedVectorWriter::isOpen() -{ - return impl_->isOpen(); -} - -/*! -@brief Return the CompressedVectorNode being written to. -@pre The associated ImageFile must be open. -@return A smart CompressedVectorNode handle referencing the underlying object -being written to. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorNode::writer -*/ -CompressedVectorNode CompressedVectorWriter::compressedVectorNode() const -{ - return impl_->compressedVectorNode(); -} - -//! @brief Diagnostic function to print internal state of object to output -//! stream in an indented format. -//! @copydetails Node::dump() -#ifdef E57_DEBUG -void CompressedVectorWriter::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void CompressedVectorWriter::dump( int indent, std::ostream &os ) const -{ -} -#endif - -//===================================================================================== -/*! -@class CompressedVectorNode -@brief An E57 element containing ordered vector of child nodes, stored in an -efficient binary format. -@details -The CompressedVectorNode encodes very long sequences of identically typed -records. In an E57 file, the per-point information (coordinates, intensity, -color, time stamp etc.) are stored in a CompressedVectorNode. For time and space -efficiency, the CompressedVectorNode data is stored in a binary section of the -E57 file. - -Conceptually, the CompressedVectorNode encodes a structure that looks very much -like a homogeneous VectorNode object. However because of the huge volume of data -(E57 files can store more than 10 billion points) within a CompressedVectorNode, -the functions for accessing the data are dramatically different. -CompressedVectorNode data is accessed in large blocks of records (100s to 1000s -at a time). - -Two attributes are required to create a new CompressedVectorNode. -The first attribute describes the shape of the record that will be stored. -This record type description is called the @c prototype of the -CompressedVectorNode. Often the @c prototype will be a StructNode with a single -level of named child elements. However, the prototype can be a tree of any depth -consisting of the following node types: IntegerNode, ScaledIntegerNode, -FloatNode, StringNode, StructureNode, or VectorNode (i.e. CompressedVectorNode -and BlobNode are not allowed). Only the node types and attributes are used in -the prototype, the values stored are ignored. For example, if the prototype -contains an IntegerNode, with a value=0, minimum=0, maximum=1023, then this -means that each record will contain an integer that can take any value in the -interval [0,1023]. As a second example, if the prototype contains an -ScaledIntegerNode, with a value=0, minimum=0, maximum=1023, scale=.001, offset=0 -then this means that each record will contain an integer that can take any value -in the interval [0,1023] and if a reader requests the scaledValue of the field, -the rawValue should be multiplied by 0.001. - -The second attribute needed to describe a new CompressedVectorNode is the @c -codecs description of how the values of the records are to be represented on the -disk. The codec object is a VectorNode of a particular format that describes the -encoding for each field in the record, which codec will be used to transfer the -values to and from the disk. Currently only one codec is defined for E57 files, -the bitPackCodec, which copies the numbers from memory, removes any unused bit -positions, and stores the without additional spaces on the disk. The -bitPackCodec has no configuration options or parameters to tune. In the ASTM -standard, if no codec is specified, the bitPackCodec is assumed. So specifying -the @c codecs as an empty VectorNode is equivalent to requesting at all fields -in the record be encoded with the bitPackCodec. - -Other than the @c prototype and @c codecs attributes, the only other state -directly accessible is the number of children (records) in the -CompressedVectorNode. The read/write access to the contents of the -CompressedVectorNode is coordinated by two other Foundation API objects: -CompressedVectorReader and CompressedVectorWriter. - -@section CompressedVectorNode_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin CompressedVectorNode::checkInvariant -@skip checkInvariant( -@until end CompressedVectorNode::checkInvariant - -@see CompressedVectorReader, CompressedVectorWriter, Node -*/ - -/*! -@brief Create an empty CompressedVectorNode, for writing, that will store -records specified by the prototype. -@param [in] destImageFile The ImageFile where the new node will eventually be -stored. -@param [in] prototype A tree that describes the fields in each record of -the CompressedVectorNode. -@param [in] codecs A VectorNode describing which codecs should be used -for each field described in the prototype. -@details -The @a destImageFile indicates which ImageFile the CompressedVectorNode will -eventually be attached to. A node is attached to an ImageFile by adding it -underneath the predefined root of the ImageFile (gotten from ImageFile::root). -It is not an error to fail to attach the CompressedVectorNode to the -@a destImageFile. It is an error to attempt to attach the CompressedVectorNode -to a different ImageFile. The CompressedVectorNode may not be written to until -it is attached to the destImageFile tree. - -The @a prototype may be any tree consisting of only the following node types: -IntegerNode, ScaledIntegerNode, FloatNode, StringNode, StructureNode, or -VectorNode (i.e. CompressedVectorNode and BlobNode are not allowed). See -CompressedVectorNode for discussion about the @a prototype argument. - -The @a codecs must be a heterogeneous VectorNode with children as specified in -the ASTM E57 data format standard. Since currently only one codec is supported -(bitPackCodec), and it is the default, passing an empty VectorNode will specify -that all record fields will be encoded with bitPackCodec. - -@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be -true). -@pre The @a destImageFile must have been opened in write mode (i.e. -destImageFile.isWritable() must be true). -@pre @a prototype must be an unattached root node (i.e. -!prototype.isAttached() && prototype.isRoot()) -@pre @a prototype cannot contain BlobNodes or CompressedVectorNodes. -@pre @a codecs must be an unattached root node (i.e. !codecs.isAttached() && -codecs.isRoot()) -@post prototype.isAttached() -@post codecs.isAttached() -@return A smart CompressedVectorNode handle referencing the underlying object. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_BAD_PROTOTYPE -@throw ::E57_ERROR_BAD_CODECS -@throw ::E57_ERROR_ALREADY_HAS_PARENT -@throw ::E57_ERROR_DIFFERENT_DEST_IMAGEFILE -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see SourceDestBuffer, Node, CompressedVectorNode::reader, CompressedVectorNode::writer -*/ -CompressedVectorNode::CompressedVectorNode( ImageFile destImageFile, const Node &prototype, const VectorNode &codecs ) : - impl_( new CompressedVectorNodeImpl( destImageFile.impl() ) ) -{ - /// Because of shared_ptr quirks, can't set prototype,codecs in - /// CompressedVectorNodeImpl(), so set it afterwards - impl_->setPrototype( prototype.impl() ); - impl_->setCodecs( codecs.impl() ); -} - -//! @brief Is this a root node. -//! @copydetails Node::isRoot() -bool CompressedVectorNode::isRoot() const -{ - return impl_->isRoot(); -} - -//! @brief Return parent of node, or self if a root node. -//! @copydetails Node::parent() -Node CompressedVectorNode::parent() const -{ - return Node( impl_->parent() ); -} - -//! @brief Get absolute pathname of node. -//! @copydetails Node::pathName() -ustring CompressedVectorNode::pathName() const -{ - return impl_->pathName(); -} - -//! @brief Get elementName string, that identifies the node in its parent.. -//! @copydetails Node::elementName() -ustring CompressedVectorNode::elementName() const -{ - return impl_->elementName(); -} - -//! @brief Get the ImageFile that was declared as the destination for the node -//! when it was created. -//! @copydetails Node::destImageFile() -ImageFile CompressedVectorNode::destImageFile() const -{ - return ImageFile( impl_->destImageFile() ); -} - -//! @brief Has node been attached into the tree of an ImageFile. -//! @copydetails Node::isAttached() -bool CompressedVectorNode::isAttached() const -{ - return impl_->isAttached(); -} - -/*! -@brief Get current number of records in a CompressedVectorNode. -@details -For a CompressedVectorNode with an active CompressedVectorWriter, the returned -number will reflect any writes completed. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return Current number of records in CompressedVectorNode. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorNode::reader, CompressedVectorNode::writer -*/ -int64_t CompressedVectorNode::childCount() const -{ - return impl_->childCount(); -} - -/*! -@brief Get the prototype tree that describes the types in the record. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return A smart Node handle referencing the root of the prototype tree. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorNode::CompressedVectorNode, SourceDestBuffer, -CompressedVectorNode::reader, CompressedVectorNode::writer -*/ -Node CompressedVectorNode::prototype() const -{ - return Node( impl_->getPrototype() ); -} - -/*! -@brief Get the codecs tree that describes the encoder/decoder configuration of -the CompressedVectorNode. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return A smart VectorNode handle referencing the root of the codecs tree. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorNode::CompressedVectorNode, SourceDestBuffer, -CompressedVectorNode::reader, CompressedVectorNode::writer -*/ -VectorNode CompressedVectorNode::codecs() const -{ - return VectorNode( impl_->getCodecs() ); -} - -//! @brief Diagnostic function to print internal state of object to output -//! stream in an indented format. -//! @copydetails Node::dump() -#ifdef E57_DEBUG -void CompressedVectorNode::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void CompressedVectorNode::dump( int indent, std::ostream &os ) const -{ -} -#endif - -/*! -@brief Upcast a CompressedVectorNode handle to a generic Node handle. -@details An upcast is always safe, and the compiler can automatically insert it -for initializations of Node variables and Node function arguments. -@return A smart Node handle referencing the underlying object. -@throw No E57Exceptions. -@see explanation in Node, Node::type(), CompressedVectorNode(const Node&) -*/ -CompressedVectorNode::operator Node() const -{ - /// Implicitly upcast from shared_ptr to - /// SharedNodeImplPtr and construct a Node object - return Node( impl_ ); -} - -/*! -@brief Downcast a generic Node handle to a CompressedVectorNode handle. -@param [in] n The generic handle to downcast. -@details The handle @a n must be for an underlying CompressedVectorNode, -otherwise an exception is thrown. In designs that need to avoid the exception, -use Node::type() to determine the actual type of the @a n before downcasting. -This function must be explicitly called (c++ compiler cannot insert it -automatically). -@return A smart CompressedVectorNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_NODE_DOWNCAST -@see Node::type(), CompressedVectorNode::operator, Node() -*/ -CompressedVectorNode::CompressedVectorNode( const Node &n ) -{ - if ( n.type() != E57_COMPRESSED_VECTOR ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_NODE_DOWNCAST, "nodeType=" + toString( n.type() ) ); - } - - /// Set our shared_ptr to the downcast shared_ptr - impl_ = std::static_pointer_cast( n.impl() ); -} - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -CompressedVectorNode::CompressedVectorNode( std::shared_ptr ni ) : impl_( ni ) -{ -} -//! @endcond - -/*! -@brief Create an iterator object for writing a series of blocks of data to a -CompressedVectorNode. -@param [in] sbufs Vector of memory buffers that will hold data to be -written to a CompressedVectorNode. -@details -See CompressedVectorWriter::write(std::vector&, unsigned) for -discussion about restrictions on @a sbufs. - -The pathNames in the @a sbufs must match one-to-one with the terminal nodes -(i.e. nodes that can have no children: IntegerNode, ScaledIntegerNode, -FloatNode, StringNode) in this CompressedVectorNode's prototype. It is an error -for two SourceDestBuffers in @a dbufs to identify the same terminal node in the -prototype. - - -It is an error to call this function if the CompressedVectorNode already has any -records (i.e. a CompressedVectorNode cannot be set twice). - -@pre @a sbufs can't be empty (i.e. sbufs.length() > 0). -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@pre The @a destImageFile must have been opened in write mode (i.e. -destImageFile.isWritable()). -@pre The destination ImageFile can't have any readers or writers open -(destImageFile().readerCount()==0 && destImageFile().writerCount()==0) -@pre This CompressedVectorNode must be attached (i.e. isAttached()). -@pre This CompressedVectorNode must have no records (i.e. childCount() == -0). -@return A smart CompressedVectorWriter handle referencing the underlying -iterator object. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_SET_TWICE -@throw ::E57_ERROR_TOO_MANY_WRITERS -@throw ::E57_ERROR_TOO_MANY_READERS -@throw ::E57_ERROR_NODE_UNATTACHED -@throw ::E57_ERROR_PATH_UNDEFINED -@throw ::E57_ERROR_BUFFER_SIZE_MISMATCH -@throw ::E57_ERROR_BUFFER_DUPLICATE_PATHNAME -@throw ::E57_ERROR_NO_BUFFER_FOR_ELEMENT -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorWriter, SourceDestBuffer, CompressedVectorNode::CompressedVectorNode, -CompressedVectorNode::prototype -*/ -CompressedVectorWriter CompressedVectorNode::writer( std::vector &sbufs ) -{ - return CompressedVectorWriter( impl_->writer( sbufs ) ); -} - -/*! -@brief Create an iterator object for reading a series of blocks of data from a -CompressedVectorNode. -@param [in] dbufs Vector of memory buffers that will receive data read -from a CompressedVectorNode. -@details -The pathNames in the @a dbufs must identify terminal nodes (i.e. node that can -have no children: IntegerNode, ScaledIntegerNode, FloatNode, StringNode) in this -CompressedVectorNode's prototype. It is an error for two SourceDestBuffers in @a -dbufs to identify the same terminal node in the prototype. It is not an error to -create a CompressedVectorReader for an empty CompressedVectorNode. - -@pre @a dbufs can't be empty -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@pre The destination ImageFile can't have any writers open -(destImageFile().writerCount()==0) -@pre This CompressedVectorNode must be attached (i.e. isAttached()). -@return A smart CompressedVectorReader handle referencing the underlying -iterator object. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_TOO_MANY_WRITERS -@throw ::E57_ERROR_NODE_UNATTACHED -@throw ::E57_ERROR_PATH_UNDEFINED -@throw ::E57_ERROR_BUFFER_SIZE_MISMATCH -@throw ::E57_ERROR_BUFFER_DUPLICATE_PATHNAME -@throw ::E57_ERROR_BAD_CV_HEADER -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorReader, SourceDestBuffer, CompressedVectorNode::CompressedVectorNode, -CompressedVectorNode::prototype -*/ -CompressedVectorReader CompressedVectorNode::reader( const std::vector &dbufs ) -{ - return CompressedVectorReader( impl_->reader( dbufs ) ); -} - -//===================================================================================== -/*! -@class IntegerNode -@brief An E57 element encoding an integer value. -@details -An IntegerNode is a terminal node (i.e. having no children) that holds an -integer value, and minimum/maximum bounds. Once the IntegerNode value and -attributes are set at creation, they may not be modified. - -The minimum attribute may be a number in the interval [-2^63, 2^63). -The maximum attribute may be a number in the interval [minimum, 2^63). -The value may be a number in the interval [minimum, maximum]. - -See Node class discussion for discussion of the common functions that -StructureNode supports. - -@section IntegerNode_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin IntegerNode::checkInvariant -@skip checkInvariant( -@until end IntegerNode::checkInvariant - -@see Node, CompressedVector -*/ - -/*! -@brief Create an E57 element for storing a integer value. -@param [in] destImageFile The ImageFile where the new node will eventually -be stored. -@param [in] value The integer value of the element. -@param [in] minimum The smallest value that the element may take. -@param [in] maximum The largest value that the element may take. -@details -An IntegerNode stores an integer value, and a lower and upper bound. -The IntegerNode class corresponds to the ASTM E57 standard Integer element. -See the class discussion at bottom of IntegerNode page for more details. - -The @a destImageFile indicates which ImageFile the IntegerNode will eventually -be attached to. A node is attached to an ImageFile by adding it underneath the -predefined root of the ImageFile (gotten from ImageFile::root). It is not an -error to fail to attach the IntegerNode to the @a destImageFile. It is an error -to attempt to attach the IntegerNode to a different ImageFile. - -@b Warning: it is an error to give an @a value outside the @a minimum / @a -maximum bounds, even if the IntegerNode is destined to be used in a -CompressedVectorNode prototype (where the @a value will be ignored). If the -IntegerNode is to be used in a prototype, it is recommended to specify a @a -value = 0 if 0 is within bounds, or a @a value = @a minimum if 0 is not within -bounds. -@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be -true). -@pre The @a destImageFile must have been opened in write mode (i.e. -destImageFile.isWritable() must be true). -@pre minimum <= value <= maximum -@return A smart IntegerNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_VALUE_OUT_OF_BOUNDS -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see IntegerNode::value, Node, CompressedVectorNode, CompressedVectorNode::prototype -*/ -IntegerNode::IntegerNode( ImageFile destImageFile, int64_t value, int64_t minimum, int64_t maximum ) : - impl_( new IntegerNodeImpl( destImageFile.impl(), value, minimum, maximum ) ) -{ -} - -//! @brief Is this a root node. -//! @copydetails Node::isRoot() -bool IntegerNode::isRoot() const -{ - return impl_->isRoot(); -} - -//! @brief Return parent of node, or self if a root node. -//! @copydetails Node::parent() -Node IntegerNode::parent() const -{ - return Node( impl_->parent() ); -} - -//! @brief Get absolute pathname of node. -//! @copydetails Node::pathName() -ustring IntegerNode::pathName() const -{ - return impl_->pathName(); -} - -//! @brief Get elementName string, that identifies the node in its parent.. -//! @copydetails Node::elementName() -ustring IntegerNode::elementName() const -{ - return impl_->elementName(); -} - -//! @brief Get the ImageFile that was declared as the destination for the node -//! when it was created. -//! @copydetails Node::destImageFile() -ImageFile IntegerNode::destImageFile() const -{ - return ImageFile( impl_->destImageFile() ); -} - -//! @brief Has node been attached into the tree of an ImageFile. -//! @copydetails Node::isAttached() -bool IntegerNode::isAttached() const -{ - return impl_->isAttached(); -} - -/*! -@brief Get integer value stored. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return integer value stored. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see IntegerNode::minimum, IntegerNode::maximum -*/ -int64_t IntegerNode::value() const -{ - return impl_->value(); -} - -/*! -@brief Get the declared minimum that the value may take. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The declared minimum that the value may take. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see IntegerCreate.cpp example, IntegerNode::value -*/ -int64_t IntegerNode::minimum() const -{ - return impl_->minimum(); -} - -/*! -@brief Get the declared maximum that the value may take. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The declared maximum that the value may take. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see IntegerNode::value -*/ -int64_t IntegerNode::maximum() const -{ - return impl_->maximum(); -} - -//! @brief Diagnostic function to print internal state of object to output -//! stream in an indented format. -//! @copydetails Node::dump() -#ifdef E57_DEBUG -void IntegerNode::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void IntegerNode::dump( int indent, std::ostream &os ) const -{ -} -#endif - -/*! -@brief Upcast a IntegerNode handle to a generic Node handle. -@details An upcast is always safe, and the compiler can automatically insert it -for initializations of Node variables and Node function arguments. -@return A smart Node handle referencing the underlying object. -@throw No E57Exceptions. -@see explanation in Node, Node::type(), IntegerNode(const Node&) -*/ -IntegerNode::operator Node() const -{ - /// Upcast from shared_ptr to SharedNodeImplPtr and - /// construct a Node object - return Node( impl_ ); -} - -/*! -@brief Downcast a generic Node handle to a IntegerNode handle. -@param [in] n The generic handle to downcast. -@details The handle @a n must be for an underlying IntegerNode, otherwise an -exception is thrown. In designs that need to avoid the exception, use -Node::type() to determine the actual type of the @a n before downcasting. This -function must be explicitly called (c++ compiler cannot insert it -automatically). -@return A smart IntegerNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_NODE_DOWNCAST -@see Node::type(), IntegerNode::operator Node() -*/ -IntegerNode::IntegerNode( const Node &n ) -{ - if ( n.type() != E57_INTEGER ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_NODE_DOWNCAST, "nodeType=" + toString( n.type() ) ); - } - - /// Set our shared_ptr to the downcast shared_ptr - impl_ = std::static_pointer_cast( n.impl() ); -} - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -IntegerNode::IntegerNode( std::shared_ptr ni ) : impl_( ni ) -{ -} -//! @endcond - -//===================================================================================== -/*! -@class ScaledIntegerNode -@brief An E57 element encoding a fixed point number. -@details -An ScaledIntegerNode is a terminal node (i.e. having no children) that holds a -fixed point number encoded by an integer @c rawValue, a double precision -floating point @c scale, an double precision floating point @c offset, and -integer minimum/maximum bounds. - -The @c minimum attribute may be a number in the interval [-2^63, 2^63). -The @c maximum attribute may be a number in the interval [minimum, 2^63). -The @c rawValue may be a number in the interval [minimum, maximum]. -The @c scaledValue is a calculated double precision floating point number -derived from: scaledValue = rawValue*scale + offset. - -See Node class discussion for discussion of the common functions that -StructureNode supports. - -@section ScaledIntegerNode_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin ScaledIntegerNode::checkInvariant -@skip checkInvariant( -@until end ScaledIntegerNode::checkInvariant - -@see Node -*/ - -/*! -@brief Create an E57 element for storing a fixed point number. -@param [in] destImageFile The ImageFile where the new node will eventually -be stored. -@param [in] rawValue The raw integer value of the element. -@param [in] minimum The smallest rawValue that the element may take. -@param [in] maximum The largest rawWalue that the element may take. -@param [in] scale The scaling factor used to compute scaledValue from -rawValue. -@param [in] offset The offset factor used to compute scaledValue from -rawValue. -@details -An ScaledIntegerNode stores an integer value, a lower and upper bound, and two -conversion factors. The ScaledIntegerNode class corresponds to the ASTM E57 -standard ScaledInteger element. See the class discussion at bottom of -ScaledIntegerNode page for more details. - -The @a destImageFile indicates which ImageFile the ScaledIntegerNode will -eventually be attached to. A node is attached to an ImageFile by adding it -underneath the predefined root of the ImageFile (gotten from ImageFile::root). -It is not an error to fail to attach the ScaledIntegerNode to the @a -destImageFile. It is an error to attempt to attach the ScaledIntegerNode to a -different ImageFile. - -@b Warning: it is an error to give an @a rawValue outside the @a minimum / @a -maximum bounds, even if the ScaledIntegerNode is destined to be used in a -CompressedVectorNode prototype (where the @a rawValue will be ignored). If the -ScaledIntegerNode is to be used in a prototype, it is recommended to specify a -@a rawValue = 0 if 0 is within bounds, or a @a rawValue = @a minimum if 0 is not -within bounds. -@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be -true). -@pre The @a destImageFile must have been opened in write mode (i.e. -destImageFile.isWritable() must be true). -@pre minimum <= rawValue <= maximum -@pre scale != 0 -@return A smart ScaledIntegerNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_VALUE_OUT_OF_BOUNDS -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ScaledIntegerNode::rawValue, Node, CompressedVectorNode, CompressedVectorNode::prototype -*/ -ScaledIntegerNode::ScaledIntegerNode( ImageFile destImageFile, int64_t rawValue, int64_t minimum, int64_t maximum, - double scale, double offset ) : - impl_( new ScaledIntegerNodeImpl( destImageFile.impl(), rawValue, minimum, maximum, scale, offset ) ) -{ -} -ScaledIntegerNode::ScaledIntegerNode( ImageFile destImageFile, int rawValue, int64_t minimum, int64_t maximum, - double scale, double offset ) : - impl_( new ScaledIntegerNodeImpl( destImageFile.impl(), static_cast( rawValue ), minimum, maximum, scale, - offset ) ) -{ -} -ScaledIntegerNode::ScaledIntegerNode( ImageFile destImageFile, int rawValue, int minimum, int maximum, double scale, - double offset ) : - impl_( new ScaledIntegerNodeImpl( destImageFile.impl(), static_cast( rawValue ), - static_cast( minimum ), static_cast( maximum ), scale, offset ) ) -{ -} -/*! -@brief This second constructor create an E57 element for storing a fixed point -number but does the scaling for you. -@param [in] destImageFile The ImageFile where the new node will eventually -be stored. -@param [in] scaledValue The scaled integer value of the element. -@param [in] scaledMinimum The smallest scaledValue that the element may -take. -@param [in] scaledMaximum The largest scaledValue that the element may take. -@param [in] scale The scaling factor used to compute scaledValue from -rawValue. -@param [in] offset The offset factor used to compute scaledValue from -rawValue. -@details -An ScaledIntegerNode stores an integer value, a lower and upper bound, and two -conversion factors. This ScaledIntegerNode constructor calculates the rawValue, -minimum, and maximum by doing the floor((scaledValue - offset)/scale + .5) on -each scaled parameters. -@b Warning: it is an error to give an @a rawValue outside the @a minimum / @a -maximum bounds, even if the ScaledIntegerNode is destined to be used in a -CompressedVectorNode prototype (where the @a rawValue will be ignored). If the -ScaledIntegerNode is to be used in a prototype, it is recommended to specify a -@a rawValue = 0 if 0 is within bounds, or a @a rawValue = @a minimum if 0 is not -within bounds. -@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be -true). -@pre The @a destImageFile must have been opened in write mode (i.e. -destImageFile.isWritable() must be true). -@pre scaledMinimum <= scaledValue <= scaledMaximum -@pre scale != 0 -@return A smart ScaledIntegerNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_VALUE_OUT_OF_BOUNDS -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ScaledIntegerNode::scaledValue, Node, CompressedVectorNode, CompressedVectorNode::prototype -*/ -ScaledIntegerNode::ScaledIntegerNode( ImageFile destImageFile, double scaledValue, double scaledMinimum, - double scaledMaximum, double scale, double offset ) : - impl_( new ScaledIntegerNodeImpl( destImageFile.impl(), scaledValue, scaledMinimum, scaledMaximum, scale, offset ) ) -{ -} -//! @brief Is this a root node. -//! @copydetails Node::isRoot() -bool ScaledIntegerNode::isRoot() const -{ - return impl_->isRoot(); -} - -//! @brief Return parent of node, or self if a root node. -//! @copydetails Node::parent() -Node ScaledIntegerNode::parent() const -{ - return Node( impl_->parent() ); -} - -//! @brief Get absolute pathname of node. -//! @copydetails Node::pathName() -ustring ScaledIntegerNode::pathName() const -{ - return impl_->pathName(); -} - -//! @brief Get elementName string, that identifies the node in its parent.. -//! @copydetails Node::elementName() -ustring ScaledIntegerNode::elementName() const -{ - return impl_->elementName(); -} - -//! @brief Get the ImageFile that was declared as the destination for the node -//! when it was created. -//! @copydetails Node::destImageFile() -ImageFile ScaledIntegerNode::destImageFile() const -{ - return ImageFile( impl_->destImageFile() ); -} - -//! @brief Has node been attached into the tree of an ImageFile. -//! @copydetails Node::isAttached() -bool ScaledIntegerNode::isAttached() const -{ - return impl_->isAttached(); -} - -/*! -@brief Get raw unscaled integer value of element. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The raw unscaled integer value stored. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ScaledIntegerNode::scaledValue, ScaledIntegerNode::minimum, ScaledIntegerNode::maximum -*/ -int64_t ScaledIntegerNode::rawValue() const -{ - return impl_->rawValue(); -} - -/*! -@brief Get scaled value of element. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The scaled value (rawValue*scale + offset) calculated from the rawValue -stored. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ScaledIntegerNode::rawValue -*/ -double ScaledIntegerNode::scaledValue() const -{ - return impl_->scaledValue(); -} - -/*! -@brief Get the declared minimum that the raw value may take. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The declared minimum that the rawValue may take. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ScaledIntegerNode::maximum, ScaledIntegerNode::rawValue -*/ -int64_t ScaledIntegerNode::minimum() const -{ - return impl_->minimum(); -} -/*! -@brief Get the declared scaled minimum that the scaled value may take. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The declared minimum that the rawValue may take. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ScaledIntegerNode::scaledMaximum, ScaledIntegerNode::scaledValue -*/ -double ScaledIntegerNode::scaledMinimum() const -{ - return impl_->scaledMinimum(); -} -/*! -@brief Get the declared maximum that the raw value may take. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The declared maximum that the rawValue may take. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ScaledIntegerNode::minimum, ScaledIntegerNode::rawValue -*/ -int64_t ScaledIntegerNode::maximum() const -{ - return impl_->maximum(); -} -/*! -@brief Get the declared scaled maximum that the scaled value may take. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The declared maximum that the rawValue may take. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ScaledIntegerNode::scaledMinimum, ScaledIntegerNode::scaledValue -*/ -double ScaledIntegerNode::scaledMaximum() const // Added by SC -{ - return impl_->scaledMaximum(); -} -/*! -@brief Get declared scaling factor. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The scaling factor used to compute scaledValue from rawValue. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ScaledIntegerNode::scaledValue -*/ -double ScaledIntegerNode::scale() const -{ - return impl_->scale(); -} - -/*! -@brief Get declared offset. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The offset used to compute scaledValue from rawValue. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ScaledIntegerNode::scaledValue -*/ -double ScaledIntegerNode::offset() const -{ - return impl_->offset(); -} - -//! @brief Diagnostic function to print internal state of object to output -//! stream in an indented format. -//! @copydetails Node::dump() -#ifdef E57_DEBUG -void ScaledIntegerNode::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void ScaledIntegerNode::dump( int indent, std::ostream &os ) const -{ -} -#endif - -/*! -@brief Upcast a ScaledIntegerNode handle to a generic Node handle. -@details An upcast is always safe, and the compiler can automatically insert it -for initializations of Node variables and Node function arguments. -@return A smart Node handle referencing the underlying object. -@throw No E57Exceptions. -@see Explanation in Node, Node::type(), ScaledIntegerNode(const Node&) -*/ -ScaledIntegerNode::operator Node() const -{ - /// Upcast from shared_ptr to SharedNodeImplPtr and - /// construct a Node object - return Node( impl_ ); -} - -/*! -@brief Downcast a generic Node handle to an ScaledIntegerNode handle. -@param [in] n The generic handle to downcast. -@details The handle @a n must be for an underlying ScaledIntegerNode, otherwise -an exception is thrown. In designs that need to avoid the exception, use -Node::type() to determine the actual type of the @a n before downcasting. This -function must be explicitly called (c++ compiler cannot insert it -automatically). -@return A smart ScaledIntegerNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_NODE_DOWNCAST -@see Node::type(), ScaledIntegerNode::operator, Node() -*/ -ScaledIntegerNode::ScaledIntegerNode( const Node &n ) -{ - if ( n.type() != E57_SCALED_INTEGER ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_NODE_DOWNCAST, "nodeType=" + toString( n.type() ) ); - } - - /// Set our shared_ptr to the downcast shared_ptr - impl_ = std::static_pointer_cast( n.impl() ); -} - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -ScaledIntegerNode::ScaledIntegerNode( std::shared_ptr ni ) : impl_( ni ) -{ -} -//! @endcond - -//===================================================================================== -/*! -@class FloatNode -@brief An E57 element encoding a single or double precision IEEE floating -point number. -@details -An FloatNode is a terminal node (i.e. having no children) that holds an IEEE -floating point value, and minimum/maximum bounds. The precision of the floating -point value and attributes may be either single or double precision. Once the -FloatNode value and attributes are set at creation, they may not be modified. - -If the precision option of the FloatNode is E57_SINGLE: -The minimum attribute may be a number in the interval -[-3.402823466e+38, 3.402823466e+38]. The maximum attribute may be a number in -the interval [maximum, 3.402823466e+38]. The value may be a number in the -interval [minimum, maximum]. - -If the precision option of the FloatNode is E57_DOUBLE: -The minimum attribute may be a number in the interval -[-1.7976931348623158e+308, 1.7976931348623158e+308]. The maximum attribute may -be a number in the interval [maximum, 1.7976931348623158e+308]. The value may be -a number in the interval [minimum, maximum]. - -See Node class discussion for discussion of the common functions that -StructureNode supports. - -@section FloatNode_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin FloatNode::checkInvariant -@skip checkInvariant( -@until end FloatNode::checkInvariant - -@see Node -*/ - -/*! -@brief Create an E57 element for storing an double precision IEEE floating -point number. -@param [in] destImageFile The ImageFile where the new node will eventually -be stored. -@param [in] value The double precision IEEE floating point value of the -element. -@param [in] precision The precision of IEEE floating point to use. May be -E57_SINGLE or E57_DOUBLE. -@param [in] minimum The smallest value that the value may take. -@param [in] maximum The largest value that the value may take. -@details -An FloatNode stores an IEEE floating point number and a lower and upper bound. -The FloatNode class corresponds to the ASTM E57 standard Float element. -See the class discussion at bottom of FloatNode page for more details. - -The @a destImageFile indicates which ImageFile the FloatNode will eventually be -attached to. A node is attached to an ImageFile by adding it underneath the -predefined root of the ImageFile (gotten from ImageFile::root). It is not an -error to fail to attach the FloatNode to the @a destImageFile. It is an error to -attempt to attach the FloatNode to a different ImageFile. - -There is only one FloatNode constructor that handles both E57_SINGLE and -E57_DOUBLE precision cases. If @a precision = E57_SINGLE, then the object will -silently round the double precision @a value to the nearest representable single -precision value. In this case, the lower bits will be lost, and if the value is -outside the representable range of a single precision number, the exponent may -be changed. The same is true for the @a minimum and @a maximum arguments. - -@b Warning: it is an error to give an @a value outside the @a minimum / @a -maximum bounds, even if the FloatNode is destined to be used in a -CompressedVectorNode prototype (where the @a value will be ignored). If the -FloatNode is to be used in a prototype, it is recommended to specify a @a value -= 0 if 0 is within bounds, or a @a value = @a minimum if 0 is not within bounds. -@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be -true). -@pre The @a destImageFile must have been opened in write mode (i.e. -destImageFile.isWritable() must be true). -@pre minimum <= value <= maximum -@return A smart FloatNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_VALUE_OUT_OF_BOUNDS -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see FloatPrecision, FloatNode::value, Node, CompressedVectorNode, CompressedVectorNode::prototype -*/ -FloatNode::FloatNode( ImageFile destImageFile, double value, FloatPrecision precision, double minimum, - double maximum ) : - impl_( new FloatNodeImpl( destImageFile.impl(), value, precision, minimum, maximum ) ) -{ -} - -//! @brief Is this a root node. -//! @copydetails Node::isRoot() -bool FloatNode::isRoot() const -{ - return impl_->isRoot(); -} - -//! @brief Return parent of node, or self if a root node. -//! @copydetails Node::parent() -Node FloatNode::parent() const -{ - return Node( impl_->parent() ); -} - -//! @brief Get absolute pathname of node. -//! @copydetails Node::pathName() -ustring FloatNode::pathName() const -{ - return impl_->pathName(); -} - -//! @brief Get elementName string, that identifies the node in its parent.. -//! @copydetails Node::elementName() -ustring FloatNode::elementName() const -{ - return impl_->elementName(); -} - -//! @brief Get the ImageFile that was declared as the destination for the node -//! when it was created. -//! @copydetails Node::destImageFile() -ImageFile FloatNode::destImageFile() const -{ - return ImageFile( impl_->destImageFile() ); -} - -//! @brief Has node been attached into the tree of an ImageFile. -//! @copydetails Node::isAttached() -bool FloatNode::isAttached() const -{ - return impl_->isAttached(); -} - -/*! -@brief Get IEEE floating point value stored. -@details -If precision is E57_SINGLE, the single precision value is returned as a double. -If precision is E57_DOUBLE, the double precision value is returned as a double. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The IEEE floating point value stored, represented as a double. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see FloatNode::minimum, FloatNode::maximum -*/ -double FloatNode::value() const -{ - return impl_->value(); -} - -/*! -@brief Get declared precision of the floating point number. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The declared precision of the floating point number, either -::E57_SINGLE or ::E57_DOUBLE. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see FloatPrecision -*/ -FloatPrecision FloatNode::precision() const -{ - return impl_->precision(); -} - -/*! -@brief Get the declared minimum that the value may take. -@details -If precision is E57_SINGLE, the single precision minimum is returned as a -double. If precision is E57_DOUBLE, the double precision minimum is returned as -a double. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The declared minimum that the value may take. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see FloatNode::maximum, FloatNode::value -*/ -double FloatNode::minimum() const -{ - return impl_->minimum(); -} - -/*! -@brief Get the declared maximum that the value may take. -@details -If precision is E57_SINGLE, the single precision maximum is returned as a -double. If precision is E57_DOUBLE, the double precision maximum is returned as -a double. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The declared maximum that the value may take. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see FloatNode::minimum, FloatNode::value -*/ -double FloatNode::maximum() const -{ - return impl_->maximum(); -} - -//! @brief Diagnostic function to print internal state of object to output -//! stream in an indented format. -//! @copydetails Node::dump() -#ifdef E57_DEBUG -void FloatNode::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void FloatNode::dump( int indent, std::ostream &os ) const -{ -} -#endif - -/*! -@brief Upcast a FloatNode handle to a generic Node handle. -@details An upcast is always safe, and the compiler can automatically insert it -for initializations of Node variables and Node function arguments. -@return A smart Node handle referencing the underlying object. -@throw No E57Exceptions. -@see Explanation in Node, Node::type() -*/ -FloatNode::operator Node() const -{ - /// Upcast from shared_ptr to SharedNodeImplPtr and construct - /// a Node object - return Node( impl_ ); -} - -/*! -@brief Downcast a generic Node handle to a FloatNode handle. -@param [in] n The generic handle to downcast. -@details The handle @a n must be for an underlying FloatNode, otherwise an -exception is thrown. In designs that need to avoid the exception, use -Node::type() to determine the actual type of the @a n before downcasting. This -function must be explicitly called (c++ compiler cannot insert it -automatically). -@return A smart FloatNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_NODE_DOWNCAST -@see Node::type(), FloatNode::operator Node() -*/ -FloatNode::FloatNode( const Node &n ) -{ - if ( n.type() != E57_FLOAT ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_NODE_DOWNCAST, "nodeType=" + toString( n.type() ) ); - } - - /// Set our shared_ptr to the downcast shared_ptr - impl_ = std::static_pointer_cast( n.impl() ); -} - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -FloatNode::FloatNode( std::shared_ptr ni ) : impl_( ni ) -{ -} -//! @endcond - -//===================================================================================== -/*! -@class StringNode -@brief An E57 element encoding a Unicode character string value. -@details -A StringNode is a terminal node (i.e. having no children) that holds an Unicode -character string encoded in UTF-8. Once the StringNode value is set at creation, -it may not be modified. - -See Node class discussion for discussion of the common functions that -StructureNode supports. - -@section StringNode_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin StringNode::checkInvariant -@skip checkInvariant( -@until end StringNode::checkInvariant - -@see Node -*/ - -/*! -@brief Create an element storing a Unicode character string. -@param [in] destImageFile The ImageFile where the new node will eventually be -stored. -@param [in] value The Unicode character string value of the element, -in UTF-8 encoding. -@details -The StringNode class corresponds to the ASTM E57 standard String element. -See the class discussion at bottom of StringNode page for more details. - -The @a destImageFile indicates which ImageFile the StringNode will eventually be -attached to. A node is attached to an ImageFile by adding it underneath the -predefined root of the ImageFile (gotten from ImageFile::root). It is not an -error to fail to attach the StringNode to the @a destImageFile. It is an error -to attempt to attach the StringNode to a different ImageFile. - -If the StringNode is to be used in a CompressedVectorNode prototype, it is -recommended to specify a -@a value = "" (the default value). -@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be -true). -@pre The @a destImageFile must have been opened in write mode (i.e. -destImageFile.isWritable() must be true). -@return A smart StringNode handle referencing the underlying object. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see StringNode::value, Node, CompressedVectorNode, CompressedVectorNode::prototype -*/ -StringNode::StringNode( ImageFile destImageFile, const ustring &value ) : - impl_( new StringNodeImpl( destImageFile.impl(), value ) ) -{ -} - -//! @brief Is this a root node. -//! @copydetails Node::isRoot() -bool StringNode::isRoot() const -{ - return impl_->isRoot(); -} - -//! @brief Return parent of node, or self if a root node. -//! @copydetails Node::parent() -Node StringNode::parent() const -{ - return Node( impl_->parent() ); -} - -//! @brief Get absolute pathname of node. -//! @copydetails Node::pathName() -ustring StringNode::pathName() const -{ - return impl_->pathName(); -} - -//! @brief Get elementName string, that identifies the node in its parent.. -//! @copydetails Node::elementName() -ustring StringNode::elementName() const -{ - return impl_->elementName(); -} - -//! @brief Get the ImageFile that was declared as the destination for the node -//! when it was created. -//! @copydetails Node::destImageFile() -ImageFile StringNode::destImageFile() const -{ - return ImageFile( impl_->destImageFile() ); -} - -//! @brief Has node been attached into the tree of an ImageFile. -//! @copydetails Node::isAttached() -bool StringNode::isAttached() const -{ - return impl_->isAttached(); -} - -/*! -@brief Get Unicode character string value stored. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The Unicode character string value stored. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -*/ -ustring StringNode::value() const -{ - return impl_->value(); -} - -//! @brief Diagnostic function to print internal state of object to output -//! stream in an indented format. -//! @copydetails Node::dump() -#ifdef E57_DEBUG -void StringNode::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void StringNode::dump( int indent, std::ostream &os ) const -{ -} -#endif - -/*! -@brief Upcast a StringNode handle to a generic Node handle. -@details An upcast is always safe, and the compiler can automatically insert it -for initializations of Node variables and Node function arguments. -@return A smart Node handle referencing the underlying object. -@throw No E57Exceptions. -@see Explanation in Node, Node::type(), StringNode(const Node&) -*/ -StringNode::operator Node() const -{ - /// Upcast from shared_ptr to SharedNodeImplPtr and construct - /// a Node object - return Node( impl_ ); -} - -/*! -@brief Downcast a generic Node handle to a StringNode handle. -@param [in] n The generic handle to downcast. -@details The handle @a n must be for an underlying StringNode, otherwise an -exception is thrown. In designs that need to avoid the exception, use -Node::type() to determine the actual type of the @a n before downcasting. This -function must be explicitly called (c++ compiler cannot insert it -automatically). -@return A smart StringNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_NODE_DOWNCAST -@see Node::type(), StringNode::operator Node() -*/ -StringNode::StringNode( const Node &n ) -{ - if ( n.type() != E57_STRING ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_NODE_DOWNCAST, "nodeType=" + toString( n.type() ) ); - } - - /// Set our shared_ptr to the downcast shared_ptr - impl_ = std::static_pointer_cast( n.impl() ); -} - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -StringNode::StringNode( std::shared_ptr ni ) : impl_( ni ) -{ -} -//! @endcond - -//===================================================================================== -/*! -@class BlobNode -@brief An E57 element encoding an fixed-length sequence of bytes with an -opaque format. -@details -A BlobNode is a terminal node (i.e. having no children) that holds an opaque, -fixed-length sequence of bytes. The number of bytes in the BlobNode is declared -at creation time. The content of the blob is stored within the E57 file in an -efficient binary format (but not compressed). The BlobNode cannot grow after it -is created. There is no ordering constraints on how content of a BlobNode may be -accessed (i.e. it is random access). BlobNodes in an ImageFile opened for -reading are read-only. - -There are two categories of BlobNodes, distinguished by their usage: private -BlobNodes and public BlobNodes. In a private BlobNode, the format of its content -bytes is not published. This is useful for storing proprietary data that a -writer does not wish to share with all readers. Rather than put this information -in a separate file, the writer can embed the file inside the E57 file so it -cannot be lost. - -In a public BlobNode, the format is published or follows some industry standard -format (e.g. JPEG). Rather than reinvent the wheel in applications that are -already well-served by an existing format standard, an E57 file writer can just -embed an existing file as an "attachment" in a BlobNode. The internal format of -a public BlobNode is not enforced by the Foundation API. It is recommended that -there be some mechanism for a reader to know ahead of time which format the -BlobNode content adheres to (either specified by a document, or encoded by some -scheme in the E57 Element tree). - -The BlobNode is the one node type where the set-once policy is not strictly -enforced. It is possible to write the same byte location in a BlobNode several -times. However it is not recommended. - -See Node class discussion for discussion of the common functions that -StructureNode supports. - -@section BlobNode_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or, can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin BlobNode::checkInvariant -@skip checkInvariant( -@until end BlobNode::checkInvariant - -@see Node -*/ - -/*! -@brief Create an element for storing a sequence of bytes with an opaque -format. -@param [in] destImageFile The ImageFile where the new node will eventually be -stored. -@param [in] byteCount The number of bytes reserved in the ImageFile for -holding the blob. -@details -The BlobNode class corresponds to the ASTM E57 standard Blob element. -See the class discussion at bottom of BlobNode page for more details. - -The E57 Foundation Implementation may pre-allocate disk space in the ImageFile -to store the declared length of the blob. The disk must have enough free space -to store @a byteCount bytes of data. The data of a newly created BlobNode is -initialized to zero. - -The @a destImageFile indicates which ImageFile the BlobNode will eventually be -attached to. A node is attached to an ImageFile by adding it underneath the -predefined root of the ImageFile (gotten from ImageFile::root). It is not an -error to fail to attach the BlobNode to the @a destImageFile. It is an error to -attempt to attach the BlobNode to a different ImageFile. -@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be -true). -@pre The @a destImageFile must have been opened in write mode (i.e. -destImageFile.isWritable() must be true). -@pre byteCount >= 0 -@return A smart BlobNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see Node, BlobNode::read, BlobNode::write -*/ -BlobNode::BlobNode( ImageFile destImageFile, int64_t byteCount ) : - impl_( new BlobNodeImpl( destImageFile.impl(), byteCount ) ) -{ -} - -//! @brief Is this a root node. -//! @copydetails Node::isRoot() -bool BlobNode::isRoot() const -{ - return impl_->isRoot(); -} - -//! @brief Return parent of node, or self if a root node. -//! @copydetails Node::parent() -Node BlobNode::parent() const -{ - return Node( impl_->parent() ); -} - -//! @brief Get absolute pathname of node. -//! @copydetails Node::pathName() -ustring BlobNode::pathName() const -{ - return impl_->pathName(); -} - -//! @brief Get elementName string, that identifies the node in its parent.. -//! @copydetails Node::elementName() -ustring BlobNode::elementName() const -{ - return impl_->elementName(); -} - -//! @brief Get the ImageFile that was declared as the destination for the node -//! when it was created. -//! @copydetails Node::destImageFile() -ImageFile BlobNode::destImageFile() const -{ - return ImageFile( impl_->destImageFile() ); -} - -//! @brief Has node been attached into the tree of an ImageFile. -//! @copydetails Node::isAttached() -bool BlobNode::isAttached() const -{ - return impl_->isAttached(); -} - -/*! -@brief Get size of blob declared when it was created. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@post No visible state is modified. -@return The declared size of the blob when it was created. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see BlobNode::read, BlobNode::write -*/ -int64_t BlobNode::byteCount() const -{ - return impl_->byteCount(); -} - -/*! -@brief Read a buffer of bytes from a blob. -@param [in] buf A memory buffer to store bytes read from the blob. -@param [in] start The index of the first byte in blob to read. -@param [in] count The number of bytes to read. -@details -The memory buffer @a buf must be able to store at least @a count bytes. -The data is stored in a binary section of the ImageFile with checksum -protection, so undetected corruption is very unlikely. It is an error to attempt -to read outside the declared size of the Blob. The format of the data read is -opaque (unspecified by the ASTM E57 data format standard). Since @a buf is a -byte buffer, byte ordering is irrelevant (it will come out in the same order -that it went in). There is no constraint on the ordering of reads. Any part of -the Blob data can be read zero or more times. -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@pre buf != NULL -@pre 0 <= @a start < byteCount() -@pre 0 <= count -@pre (@a start + @a count) < byteCount() -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_LSEEK_FAILED -@throw ::E57_ERROR_READ_FAILED -@throw ::E57_ERROR_BAD_CHECKSUM -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see BlobNode::byteCount, BlobNode::write -*/ -void BlobNode::read( uint8_t *buf, int64_t start, size_t count ) -{ - impl_->read( buf, start, count ); -} - -/*! -@brief Write a buffer of bytes to a blob. -@param [in] buf A memory buffer of bytes to write to the blob. -@param [in] start The index of the first byte in blob to write to. -@param [in] count The number of bytes to write. -@details -The memory buffer @a buf must store at least @a count bytes. -The data is stored in a binary section of the ImageFile with checksum -protection, so undetected corruption is very unlikely. It is an error to attempt -to write outside the declared size of the Blob. The format of the data written -is opaque (unspecified by the ASTM E57 data format standard). Since @a buf is a -byte buffer, byte ordering is irrelevant (it will come out in the same order -that it went in). There is no constraint on the ordering of writes. It is not an -error to write a portion of the BlobNode data more than once, or not at all. -Initially all the BlobNode data is zero, so if a portion is not written, it will -remain zero. The BlobNode is one of the two node types that must be attached to -the root of a write mode ImageFile before write operations can be performed (the -other type is CompressedVectorNode). -@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). -@pre The associated destImageFile must have been opened in write mode (i.e. -destImageFile().isWritable()). -@pre The BlobNode must be attached to an ImageFile (i.e. isAttached()). -@pre buf != NULL -@pre 0 <= @a start < byteCount() -@pre 0 <= count -@pre (@a start + @a count) < byteCount() -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_NODE_UNATTACHED -@throw ::E57_ERROR_LSEEK_FAILED -@throw ::E57_ERROR_READ_FAILED -@throw ::E57_ERROR_WRITE_FAILED -@throw ::E57_ERROR_BAD_CHECKSUM -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see BlobNode::byteCount, BlobNode::read -*/ -void BlobNode::write( uint8_t *buf, int64_t start, size_t count ) -{ - impl_->write( buf, start, count ); -} - -//! @brief Diagnostic function to print internal state of object to output -//! stream in an indented format. -//! @copydetails Node::dump() -#ifdef E57_DEBUG -void BlobNode::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void BlobNode::dump( int indent, std::ostream &os ) const -{ -} -#endif - -/*! -@brief Upcast a BlobNode handle to a generic Node handle. -@details An upcast is always safe, and the compiler can automatically insert it -for initializations of Node variables and Node function arguments. -@return A smart Node handle referencing the underlying object. -@throw No E57Exceptions. -@see Explanation in Node, Node::type(), BlobNode(const Node&) -*/ -BlobNode::operator Node() const -{ - /// Upcast from shared_ptr to SharedNodeImplPtr and construct - /// a Node object - return Node( impl_ ); -} - -/*! -@brief Downcast a generic Node handle to a BlobNode handle. -@param [in] n The generic handle to downcast. -@details The handle @a n must be for an underlying BlobNode, otherwise an -exception is thrown. In designs that need to avoid the exception, use -Node::type() to determine the actual type of the @a n before downcasting. This -function must be explicitly called (c++ compiler cannot insert it -automatically). -@return A smart BlobNode handle referencing the underlying object. -@throw ::E57_ERROR_BAD_NODE_DOWNCAST -@see Node::type(), BlobNode::operator Node() -*/ -BlobNode::BlobNode( const Node &n ) -{ - if ( n.type() != E57_BLOB ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_NODE_DOWNCAST, "nodeType=" + toString( n.type() ) ); - } - - /// Set our shared_ptr to the downcast shared_ptr - impl_ = std::static_pointer_cast( n.impl() ); -} - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -BlobNode::BlobNode( ImageFile destImageFile, int64_t fileOffset, int64_t length ) : - impl_( new BlobNodeImpl( destImageFile.impl(), fileOffset, length ) ) -{ -} - -BlobNode::BlobNode( std::shared_ptr ni ) : impl_( ni ) -{ -} -//! @endcond - -//===================================================================================== -/*! -@class ImageFile -@brief An ASTM E57 3D format file object. -@details -@section imagefile_ClassOverview Class overview -The ImageFile class represents the state of an ASTM E57 format data file. -An ImageFile may be created from an E57 file on the disk (read mode). -An new ImageFile may be created to write an E57 file to disk (write mode). - -E57 files are organized in a tree structure. -Each ImageFile object has a predefined root node (of type StructureNode). -In a write mode ImageFile, the root node is initially empty. -In a read mode ImageFile, the root node is populated by the tree stored in the -.e57 file on disk. - -@section imagefile_OpenClose The open/close state -An ImageFile object, opened in either mode (read/write), can be in one of two -states: open or closed. An ImageFile in the open state is ready to perform -transfers of data and to be interrogated. An ImageFile in the closed state -cannot perform any further transfers, and has very limited ability to be -interrogated. Note entering the closed state is different than destroying the -ImageFile object. An ImageFile object can still exist and be in the closed -state. When created, the ImageFile is initially open. - -The ImageFile state can transition to the closed state in two ways. -The programmer can call ImageFile::close after all required processing has -completed. The programmer can call ImageFile::cancel if it is determined that -the ImageFile is no longer needed. - -@section imagefile_Extensions Extensions - -Basically in an E57 file, "extension = namespace + rules + meaning". -The "namespace" ensures that element names don't collide. -The "rules" may be written on paper, or partly codified in a computer grammar. -The "meaning" is a definition of what was measured, what the numbers in the file -mean. - -Extensions are identified by URIs. -Extensions are not identified by prefixes. -Prefixes are a shorthand, used in a particular file, to make the element names -more palatable for humans. When thinking about a prefixed element name, in your -mind you should immediately substitute the URI for the prefix. For example, -think "http://www.example.com/DemoExtension:extra2" rather than "demo:extra2", -if the prefix "demo" is declared in the file to be a shorthand for the URI -"http://www.example.com/DemoExtension". - -The rules are statements of: what is valid, what element names are possible, -what values are possible. The rules establish the answer to the following yes/no -question: "Is this extended E57 file valid?". The rules divide all possible -files into two sets: valid files and invalid files. - -The "meanings" part of the above equation defines what the files in the first -set, the valid files, actually mean. This definition usually comes in the form -of documentation of the content of each new element in the format and how they -relate to the other elements. - -An element name in an E57 file is a member of exactly one namespace (either the -default namespace defined in the ASTM standard, or an extension namespace). -Rules about the structure of an E57 extension (what element names can appear -where), are implicitly assumed only to govern the element names within the -namespace of the extension. Element names in other namespaces are unconstrained. -This is because a reader is required to ignore elements in namespaces that are -unfamiliar (to treat them as if they didn't exist). This enables a writer to -"tack on" new elements into pre-defined structures (e.g. structures defined in -the ASTM standard), without fear that it will confuse a reader that is only -familiar with the old format. This allows an extension designer to communicate -to two sets of readers: the old readers that will understand the information in -the old base format, and the new-fangled readers that will be able to read the -base format and the extra information stored in element names in the extended -namespace. - -@section ImageFile_invariant Class Invariant -A class invariant is a list of statements about an object that are always true -before and after any operation on the object. An invariant is useful for testing -correct operation of an implementation. Statements in an invariant can involve -only externally visible state, or can refer to internal implementation-specific -state that is not visible to the API user. The following C++ code checks -externally visible state for consistency and throws an exception if the -invariant is violated: -@dontinclude E57Format.cpp -@skip begin ImageFile::checkInvariant -@skip checkInvariant( -@until end ImageFile::checkInvariant -*/ - -/*! -@brief Open an ASTM E57 imaging data file for reading/writing. -@param [in] fname File name to open. -Support of '\' as a directory separating character is system dependent. -For maximum portability, it is recommended that '/' be used as a directory -separator in file names. Special device file name support are implementation -dependent (e.g. "\\.\PhysicalDrive3" or -"/dev/hd3"). It is recommended that files that meet all of the requirements for -a legal ASTM E57 file format use the extension @c ".e57". It is recommended that -files that utilize the low-level E57 element data types, but do not have all the -required element names required by ASTM E57 file format standard use the file -extension @c "._e57". -@param [in] mode Either "w" for writing or "r" for reading. -@param [in] checksumPolicy The percentage of checksums we compute and verify -as an int. Clamped to 0-100. -@details - -@par Write Mode -In write mode, the file cannot be already open. -A file with name given by @a fname is immediately created on the disk. -This file may grow as a result of operations on the ImageFile. -Which API functions write data to the file are implementation dependent. -Thus any API operation that stores data may fail as a result of insufficient -free disk space. Read API operations are legal for an ImageFile opened in write -mode. - -@par Read Mode -Read mode files may be shared. -Write API operations are not legal for an ImageFile opened in read mode (i.e. -the ImageFile is read-only). There is no API support for appending data onto an -existing E57 data file. - -@post Resulting ImageFile is in @c open state if constructor succeeds (no -exception thrown). -@return A smart ImageFile handle referencing the underlying object. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_OPEN_FAILED -@throw ::E57_ERROR_LSEEK_FAILED -@throw ::E57_ERROR_READ_FAILED -@throw ::E57_ERROR_WRITE_FAILED -@throw ::E57_ERROR_BAD_CHECKSUM -@throw ::E57_ERROR_BAD_FILE_SIGNATURE -@throw ::E57_ERROR_UNKNOWN_FILE_VERSION -@throw ::E57_ERROR_BAD_FILE_LENGTH -@throw ::E57_ERROR_XML_PARSER_INIT -@throw ::E57_ERROR_XML_PARSER -@throw ::E57_ERROR_BAD_XML_FORMAT -@throw ::E57_ERROR_BAD_CONFIGURATION -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see IntegerNode, ScaledIntegerNode, FloatNode, -StringNode, BlobNode, StructureNode, VectorNode, CompressedVectorNode, -E57Exception, E57Utilities::E57Utilities -*/ -ImageFile::ImageFile( const ustring &fname, const ustring &mode, ReadChecksumPolicy checksumPolicy ) : - impl_( new ImageFileImpl( checksumPolicy ) ) -{ - /// Do second phase of construction, now that ImageFile object is complete. - impl_->construct2( fname, mode ); -} - -ImageFile::ImageFile( const char *input, const uint64_t size, ReadChecksumPolicy checksumPolicy ) : - impl_( new ImageFileImpl( checksumPolicy ) ) -{ - impl_->construct2( input, size ); -} - -/*! -@brief Get the pre-established root StructureNode of the E57 ImageFile. -@details The root node of an ImageFile always exists and is always type -StructureNode. The root node is empty in a newly created write mode ImageFile. -@pre This ImageFile must be open (i.e. isOpen()). -@return A smart StructureNode handle referencing the underlying object. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see StructureNode. -*/ -StructureNode ImageFile::root() const -{ - return StructureNode( impl_->root() ); -} - -/*! -@brief Complete any write operations on an ImageFile, and close the file on -the disk. -@details -Completes the writing of the state of the ImageFile to the disk. -Some API implementations may store significant portions of the state of the -ImageFile in memory. This state is moved into the disk file before it is closed. -Any errors in finishing the writing are reported by throwing an exception. -If an exception is thrown, depending on the error code, the ImageFile may enter -the closed state. If no exception is thrown, then the file on disk will be an -accurate representation of the ImageFile. - -@b Warning: if the ImageFile::close function is not called, and the ImageFile -destructor is invoked with the ImageFile in the open state, the associated disk -file will be deleted and the ImageFile will @em not be saved to the disk (the -same outcome as calling ImageFile::cancel). The reason for this is that any -error conditions can't be reported from a destructor, so the user can't be -assured that the destruction/close completed successfully. It is strongly -recommended that this close function be called before the ImageFile is -destroyed. - -It is not an error if ImageFile is already closed. -@post ImageFile is in @c closed state. -@throw ::E57_ERROR_LSEEK_FAILED -@throw ::E57_ERROR_READ_FAILED -@throw ::E57_ERROR_WRITE_FAILED -@throw ::E57_ERROR_CLOSE_FAILED -@throw ::E57_ERROR_BAD_CHECKSUM -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ImageFile::cancel, ImageFile::isOpen -*/ -void ImageFile::close() -{ - impl_->close(); -} - -/*! -@brief Stop I/O operations and delete a partially written ImageFile on the -disk. -@details -If the ImageFile is write mode, the associated file on the disk is closed and -deleted, and the ImageFile goes to the closed state. If the ImageFile is read -mode, the behavior is same as calling ImageFile::close, but no exceptions are -thrown. It is not an error if ImageFile is already closed. -@post ImageFile is in @c closed state. -@throw No E57Exceptions. -@see ImageFile::ImageFile, ImageFile::close, ImageFile::isOpen -*/ -void ImageFile::cancel() -{ - impl_->cancel(); -} - -/*! -@brief Test whether ImageFile is still open for accessing. -@post No visible state is modified. -@return true if ImageFile is in @c open state. -@throw No E57Exceptions. -@see ImageFile::ImageFile, ImageFile::close -*/ -bool ImageFile::isOpen() const -{ - return impl_->isOpen(); -} - -/*! -@brief Test whether ImageFile was opened in write mode. -@post No visible state is modified. -@return true if ImageFile was opened in write mode. -@throw No E57Exceptions. -@see ImageFile::ImageFile, ImageFile::isOpen -*/ -bool ImageFile::isWritable() const -{ - return impl_->isWriter(); -} - -/*! -@brief Get the file name the ImageFile was created with. -@post No visible state is modified. -@return The file name the ImageFile was created with. -@throw No E57Exceptions. -@see Cancel.cpp example, ImageFile::ImageFile -*/ -ustring ImageFile::fileName() const -{ - return impl_->fileName(); -} - -/*! -@brief Get current number of open CompressedVectorWriter objects writing to -ImageFile. -@details -CompressedVectorWriter objects that still exist, but are in the closed state -aren't counted. CompressedVectorWriter objects are created by the -CompressedVectorNode::writer function. -@pre This ImageFile must be open (i.e. isOpen()). -@post No visible state is modified. -@return The current number of open CompressedVectorWriter objects writing to -ImageFile. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorNode::writer, CompressedVectorWriter -*/ -int ImageFile::writerCount() const -{ - return impl_->writerCount(); -} - -/*! -@brief Get current number of open CompressedVectorReader objects reading from -ImageFile. -@details -CompressedVectorReader objects that still exist, but are in the closed state -aren't counted. CompressedVectorReader objects are created by the -CompressedVectorNode::reader function. -@pre This ImageFile must be open (i.e. isOpen()). -@post No visible state is modified. -@return The current number of open CompressedVectorReader objects reading from -ImageFile. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see CompressedVectorNode::reader, CompressedVectorReader -*/ -int ImageFile::readerCount() const -{ - return impl_->readerCount(); -} - -/*! -@brief Declare the use of an E57 extension in an ImageFile being written. -@param [in] prefix The shorthand name of the extension to use in element -names. -@param [in] uri The Uniform Resource Identifier string to associate with -the prefix in the ImageFile. -@details -The (@a prefix, @a uri) pair is registered in the known extensions of the -ImageFile. Both @a prefix and @a uri must be unique in the ImageFile. It is not -legal to declare a URI associated with the default namespace (@a prefix = ""). -It is not an error to declare a namespace and not use it in an element name. -It is an error to use a namespace prefix in an element name that is not declared -beforehand. - -A writer is free to "hard code" the prefix names in the element name strings -that it uses (since it established the prefix declarations in the file). A -reader cannot assume that any given prefix is always mapped to the same URI or -vice versa. A reader might check an ImageFile, and if the prefixes aren't the -way it likes, the reader could give up. - -A better scheme would be to lookup the URI that the reader is familiar with, and -store the prefix that the particular file uses in a variable. Then every time -the reader needs to form a prefixed element name, it can assemble the full -element name from the stored prefix variable and the constant documented base -name string. This is less convenient than using a single "hard coded" string -constant for an element name, but it is robust against any choice of prefix/URI -combination. - -See the class discussion at bottom of ImageFile page for more details about -namespaces. -@pre This ImageFile must be open (i.e. isOpen()). -@pre ImageFile must have been opened in write mode (i.e. isWritable()). -@pre prefix != "" -@pre uri != "" -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_FILE_IS_READ_ONLY -@throw ::E57_ERROR_DUPLICATE_NAMESPACE_PREFIX -@throw ::E57_ERROR_DUPLICATE_NAMESPACE_URI -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ImageFile::extensionsCount, ImageFile::extensionsLookupPrefix, ImageFile::extensionsLookupUri -*/ -void ImageFile::extensionsAdd( const ustring &prefix, const ustring &uri ) -{ - impl_->extensionsAdd( prefix, uri ); -} - -/*! -@brief Get URI associated with an E57 extension prefix in the ImageFile. -@param [in] prefix The shorthand name of the extension to look up. -@param [out] uri The URI that was associated with the given @a prefix. -@details -If @a prefix = "", then @a uri is set to the default namespace URI, and the -function returns true. if @a prefix is declared in the ImageFile, then @a uri is -set the corresponding URI, and the function returns true. It is an error if @a -prefix contains an illegal character combination for E57 namespace prefixes. It -is not an error if @a prefix is well-formed, but not defined in the ImageFile -(the function just returns false). -@pre This ImageFile must be open (i.e. isOpen()). -@post No visible state is modified. -@return true if prefix is declared in the ImageFile. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ImageFile::extensionsLookupUri -*/ -bool ImageFile::extensionsLookupPrefix( const ustring &prefix, ustring &uri ) const -{ - return impl_->extensionsLookupPrefix( prefix, uri ); -} - -/*! -@brief Get an E57 extension prefix associated with a URI in the ImageFile. -@param [in] uri The URI of the extension to look up. -@param [out] prefix The shorthand prefix that was associated with the given -@a uri. -@details -If @a uri is declared in the ImageFile, then @a prefix is set the corresponding -prefix, and the function returns true. It is an error if @a uri contains an -illegal character combination for E57 namespace URIs. It is not an error if @a -uri is well-formed, but not defined in the ImageFile (the function just returns -false). -@pre This ImageFile must be open (i.e. isOpen()). -@pre uri != "" -@post No visible state is modified. -@return true if URI is declared in the ImageFile. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ImageFile::extensionsLookupPrefix -*/ -bool ImageFile::extensionsLookupUri( const ustring &uri, ustring &prefix ) const -{ - return impl_->extensionsLookupUri( uri, prefix ); -} - -/*! -@brief Get number of E57 extensions declared in the ImageFile. -@details -The default E57 namespace does not count as an extension. -@pre This ImageFile must be open (i.e. isOpen()). -@post No visible state is modified. -@return The number of E57 extensions defined in the ImageFile. -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ImageFile::extensionsPrefix, ImageFile::extensionsUri -*/ -size_t ImageFile::extensionsCount() const -{ - return impl_->extensionsCount(); -} - -/*! -@brief Get an E57 extension prefix declared in an ImageFile by index. -@param [in] index The index of the prefix to get, starting at 0. -@details -The order that the prefixes are stored in is not necessarily the same as the -order they were created. However the prefix order will correspond to the URI -order. The default E57 namespace is not counted as an extension. -@pre This ImageFile must be open (i.e. isOpen()). -@pre 0 <= index < extensionsCount() -@post No visible state is modified. -@return The E57 extension prefix at the given index. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ImageFile::extensionsCount, ImageFile::extensionsUri -*/ -ustring ImageFile::extensionsPrefix( const size_t index ) const -{ - return impl_->extensionsPrefix( index ); -} - -/*! -@brief Get an E57 extension URI declared in an ImageFile by index. -@param [in] index The index of the URI to get, starting at 0. -@details -The order that the URIs are stored is not necessarily the same as the order they -were created. However the URI order will correspond to the prefix order. The -default E57 namespace is not counted as an extension. -@pre This ImageFile must be open (i.e. isOpen()). -@pre 0 <= index < extensionsCount() -@post No visible state is modified. -@return The E57 extension URI at the given index. -@throw ::E57_ERROR_BAD_API_ARGUMENT -@throw ::E57_ERROR_IMAGEFILE_NOT_OPEN -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ImageFile::extensionsCount, ImageFile::extensionsPrefix -*/ -ustring ImageFile::extensionsUri( const size_t index ) const -{ - return impl_->extensionsUri( index ); -} - -/*! -@brief Test whether an E57 element name has an extension prefix. -@details -The element name has a prefix if the function -elementNameParse(elementName,prefix,dummy) would succeed, and returned prefix != -"". -@param [in] elementName The string element name to test. -@post No visible state is modified. -@return True if the E57 element name has an extension prefix. -@throw No E57Exceptions. -*/ -bool ImageFile::isElementNameExtended( const ustring &elementName ) const -{ - return impl_->isElementNameExtended( elementName ); -} - -/*! -@brief Parse element name into prefix and localPart substrings. -@param [in] elementName The string element name to parse into prefix and -local parts. -@param [out] prefix The prefix (if any) in the @a elementName. -@param [out] localPart The part of the element name after the prefix. -@details -A legal element name may be in prefixed (ID:ID) or unprefixed (ID) form, -where ID is a string whose first character is in {a-z,A-Z,_} followed by zero or -more characters in {a-z,A-Z,_,0-9,-,.}. If in prefixed form, the prefix does not -have to be declared in the ImageFile. -@post No visible state is modified. -@throw ::E57_ERROR_BAD_PATH_NAME -@throw ::E57_ERROR_INTERNAL All objects in undocumented state -@see ImageFile::isElementNameExtended -*/ -void ImageFile::elementNameParse( const ustring &elementName, ustring &prefix, ustring &localPart ) const -{ - impl_->elementNameParse( elementName, prefix, localPart ); -} - -/*! -@brief Diagnostic function to print internal state of object to output stream -in an indented format. -@copydetails Node::dump() -*/ -#ifdef E57_DEBUG -void ImageFile::dump( int indent, std::ostream &os ) const -{ - impl_->dump( indent, os ); -} -#else -void ImageFile::dump( int indent, std::ostream &os ) const -{ -} -#endif - -/*! -@brief Test if two ImageFile handles refer to the same underlying ImageFile -@param [in] imf2 The ImageFile to compare this ImageFile with -@post No visible object state is modified. -@return @c true if ImageFile handles refer to the same underlying ImageFile. -@throw No E57Exceptions -*/ -bool ImageFile::operator==( ImageFile imf2 ) const -{ - return ( impl_ == imf2.impl_ ); -} - -/*! -@brief Test if two ImageFile handles refer to different underlying ImageFile -@param [in] imf2 The ImageFile to compare this ImageFile with -@post No visible object state is modified. -@return @c true if ImageFile handles refer to different underlying ImageFiles. -@throw No E57Exceptions -*/ -bool ImageFile::operator!=( ImageFile imf2 ) const -{ - return ( impl_ != imf2.impl_ ); -} - -//! @cond documentNonPublic The following isn't part of the API, and isn't -//! documented. -ImageFile::ImageFile( ImageFileImplSharedPtr imfi ) : impl_( imfi ) -{ -} -//! @endcond diff --git a/src/3rdParty/libE57Format/src/E57SimpleData.cpp b/src/3rdParty/libE57Format/src/E57SimpleData.cpp index 20de2084ec6f3..7bb73c32f927c 100644 --- a/src/3rdParty/libE57Format/src/E57SimpleData.cpp +++ b/src/3rdParty/libE57Format/src/E57SimpleData.cpp @@ -1,25 +1,257 @@ // SPDX-License-Identifier: BSL-1.0 // Copyright (c) 2020 PTC Inc. +// Copyright (c) 2022 Andy Maloney -// for M_PI. This needs to be first, otherwise we might already include math header -// without M_PI and we would get nothing because of the header guards. +// For M_PI. This needs to be first, otherwise we might already include math header without M_PI and +// we would get nothing because of the header guards. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c) #define _USE_MATH_DEFINES #include #include "E57SimpleData.h" +#include "Common.h" +#include "StringFunctions.h" + namespace e57 { + /// Validates a Data3D and throws on error. + void _validateData3D( const Data3D &inData3D ) + { + if ( inData3D.pointCount < 1 ) + { + throw E57_EXCEPTION2( ErrorValueOutOfBounds, + "pointCount=" + toString( inData3D.pointCount ) + " minimum=1" ); + } - // To avoid exposing M_PI, we define the constructor here. + if ( inData3D.pointFields.pointRangeNodeType == NumericalNodeType::Integer ) + { + throw E57_EXCEPTION2( ErrorInvalidNodeType, "pointRangeNodeType cannot be Integer" ); + } + + if ( inData3D.pointFields.angleNodeType == NumericalNodeType::Integer ) + { + throw E57_EXCEPTION2( ErrorInvalidNodeType, "angleNodeType cannot be Integer" ); + } + } + + /// To avoid exposing M_PI, we define the constructor here. SphericalBounds::SphericalBounds() { rangeMinimum = 0.; - rangeMaximum = E57_DOUBLE_MAX; + rangeMaximum = DOUBLE_MAX; azimuthStart = -M_PI; azimuthEnd = M_PI; - elevationMinimum = -M_PI / 2.; - elevationMaximum = M_PI / 2.; + + constexpr auto HALF_PI = M_PI / 2.0; + + elevationMinimum = -HALF_PI; + elevationMaximum = HALF_PI; + } + + template + Data3DPointsData_t::Data3DPointsData_t( Data3D &data3D ) : _selfAllocated( true ) + { + static_assert( std::is_floating_point::value, "Floating point type required." ); + + _validateData3D( data3D ); + + constexpr bool cIsFloat = std::is_same::value; + + // We need to adjust min/max for floats. + if ( cIsFloat ) + { + data3D.pointFields.pointRangeMinimum = FLOAT_MIN; + data3D.pointFields.pointRangeMaximum = FLOAT_MAX; + data3D.pointFields.angleMinimum = FLOAT_MIN; + data3D.pointFields.angleMaximum = FLOAT_MAX; + data3D.pointFields.timeMinimum = FLOAT_MIN; + data3D.pointFields.timeMaximum = FLOAT_MAX; + } + + // IF point range node type is not ScaledInteger + // THEN make sure the proper floating point type is set + if ( data3D.pointFields.pointRangeNodeType != NumericalNodeType::ScaledInteger ) + { + data3D.pointFields.pointRangeNodeType = + ( cIsFloat ? NumericalNodeType::Float : NumericalNodeType::Double ); + } + + // IF angle node type is not ScaledInteger + // THEN make sure the proper floating point type is set + if ( data3D.pointFields.angleNodeType != NumericalNodeType::ScaledInteger ) + { + data3D.pointFields.angleNodeType = + ( cIsFloat ? NumericalNodeType::Float : NumericalNodeType::Double ); + } + + const auto cPointCount = data3D.pointCount; + + if ( data3D.pointFields.cartesianXField ) + { + cartesianX = new COORDTYPE[cPointCount]; + } + + if ( data3D.pointFields.cartesianYField ) + { + cartesianY = new COORDTYPE[cPointCount]; + } + + if ( data3D.pointFields.cartesianZField ) + { + cartesianZ = new COORDTYPE[cPointCount]; + } + + if ( data3D.pointFields.cartesianInvalidStateField ) + { + cartesianInvalidState = new int8_t[cPointCount]; + } + + if ( data3D.pointFields.intensityField ) + { + intensity = new double[cPointCount]; + } + + if ( data3D.pointFields.isIntensityInvalidField ) + { + isIntensityInvalid = new int8_t[cPointCount]; + } + + if ( data3D.pointFields.colorRedField ) + { + colorRed = new uint16_t[cPointCount]; + } + + if ( data3D.pointFields.colorGreenField ) + { + colorGreen = new uint16_t[cPointCount]; + } + + if ( data3D.pointFields.colorBlueField ) + { + colorBlue = new uint16_t[cPointCount]; + } + + if ( data3D.pointFields.isColorInvalidField ) + { + isColorInvalid = new int8_t[cPointCount]; + } + + if ( data3D.pointFields.sphericalRangeField ) + { + sphericalRange = new COORDTYPE[cPointCount]; + } + + if ( data3D.pointFields.sphericalAzimuthField ) + { + sphericalAzimuth = new COORDTYPE[cPointCount]; + } + + if ( data3D.pointFields.sphericalElevationField ) + { + sphericalElevation = new COORDTYPE[cPointCount]; + } + + if ( data3D.pointFields.sphericalInvalidStateField ) + { + sphericalInvalidState = new int8_t[cPointCount]; + } + + if ( data3D.pointFields.rowIndexField ) + { + rowIndex = new int32_t[cPointCount]; + } + + if ( data3D.pointFields.columnIndexField ) + { + columnIndex = new int32_t[cPointCount]; + } + + if ( data3D.pointFields.returnIndexField ) + { + returnIndex = new int8_t[cPointCount]; + } + + if ( data3D.pointFields.returnCountField ) + { + returnCount = new int8_t[cPointCount]; + } + + if ( data3D.pointFields.timeStampField ) + { + timeStamp = new double[cPointCount]; + } + + if ( data3D.pointFields.isTimeStampInvalidField ) + { + isTimeStampInvalid = new int8_t[cPointCount]; + } + + if ( data3D.pointFields.normalXField ) + { + normalX = new float[cPointCount]; + } + + if ( data3D.pointFields.normalYField ) + { + normalY = new float[cPointCount]; + } + + if ( data3D.pointFields.normalZField ) + { + normalZ = new float[cPointCount]; + } + } + + template Data3DPointsData_t::~Data3DPointsData_t() + { + static_assert( std::is_floating_point::value, "Floating point type required." ); + + if ( !_selfAllocated ) + { + return; + } + + delete[] cartesianX; + delete[] cartesianY; + delete[] cartesianZ; + delete[] cartesianInvalidState; + + delete[] intensity; + delete[] isIntensityInvalid; + + delete[] colorRed; + delete[] colorGreen; + delete[] colorBlue; + delete[] isColorInvalid; + + delete[] sphericalRange; + delete[] sphericalAzimuth; + delete[] sphericalElevation; + delete[] sphericalInvalidState; + + delete[] rowIndex; + delete[] columnIndex; + + delete[] returnIndex; + delete[] returnCount; + + delete[] timeStamp; + delete[] isTimeStampInvalid; + + delete[] normalX; + delete[] normalY; + delete[] normalZ; + + // Set them all to nullptr. + *this = Data3DPointsData_t(); } +#if defined( _MSC_VER ) + template struct E57_DLL Data3DPointsData_t; + template struct E57_DLL Data3DPointsData_t; +#else + template struct Data3DPointsData_t; + template struct Data3DPointsData_t; +#endif } // end namespace e57 diff --git a/src/3rdParty/libE57Format/src/E57SimpleReader.cpp b/src/3rdParty/libE57Format/src/E57SimpleReader.cpp index b2ca2207f1f6c..a92689bb10f0a 100644 --- a/src/3rdParty/libE57Format/src/E57SimpleReader.cpp +++ b/src/3rdParty/libE57Format/src/E57SimpleReader.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) 2010 Stan Coleby (scoleby@intelisum.com) * Copyright (c) 2020 PTC Inc. + * Copyright (c) 2022 Andy Maloney * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by @@ -30,54 +31,67 @@ namespace e57 { + Reader::Reader( const ustring &filePath, const ReaderOptions &options ) : + impl_( new ReaderImpl( filePath, options ) ) + { + } - Reader::Reader( const ustring &filePath ) : impl_( new ReaderImpl( filePath ) ) + // Note that this constructor is deprecated (see header). + Reader::Reader( const ustring &filePath ) : Reader( filePath, {} ) { } bool Reader::IsOpen() const { return impl_->IsOpen(); - }; + } bool Reader::Close() { return impl_->Close(); - }; + } bool Reader::GetE57Root( E57Root &fileHeader ) const { return impl_->GetE57Root( fileHeader ); - }; + } int64_t Reader::GetImage2DCount() const { return impl_->GetImage2DCount(); - }; + } bool Reader::ReadImage2D( int64_t imageIndex, Image2D &image2DHeader ) const { return impl_->ReadImage2D( imageIndex, image2DHeader ); - }; + } - bool Reader::GetImage2DSizes( int64_t imageIndex, Image2DProjection &imageProjection, Image2DType &imageType, - int64_t &imageWidth, int64_t &imageHeight, int64_t &imageSize, - Image2DType &imageMaskType, Image2DType &imageVisualType ) const + bool Reader::GetImage2DSizes( int64_t imageIndex, Image2DProjection &imageProjection, + Image2DType &imageType, int64_t &imageWidth, int64_t &imageHeight, + int64_t &imageSize, Image2DType &imageMaskType, + Image2DType &imageVisualType ) const { - return impl_->GetImage2DSizes( imageIndex, imageProjection, imageType, imageWidth, imageHeight, imageSize, - imageMaskType, imageVisualType ); - }; + return impl_->GetImage2DSizes( imageIndex, imageProjection, imageType, imageWidth, + imageHeight, imageSize, imageMaskType, imageVisualType ); + } - int64_t Reader::ReadImage2DData( int64_t imageIndex, Image2DProjection imageProjection, Image2DType imageType, - void *pBuffer, int64_t start, int64_t count ) const + int64_t Reader::ReadImage2DData( int64_t imageIndex, Image2DProjection imageProjection, + Image2DType imageType, void *pBuffer, int64_t start, + int64_t count ) const { - return impl_->ReadImage2DData( imageIndex, imageProjection, imageType, pBuffer, start, count ); - }; + auto *buffer = static_cast( pBuffer ); + const auto size = static_cast( count ); + + const size_t read = + impl_->ReadImage2DData( imageIndex, imageProjection, imageType, buffer, start, size ); + + return static_cast( read ); + } int64_t Reader::GetData3DCount() const { return impl_->GetData3DCount(); - }; + } ImageFile Reader::GetRawIMF() const { @@ -87,45 +101,47 @@ namespace e57 StructureNode Reader::GetRawE57Root() const { return impl_->GetRawE57Root(); - }; + } VectorNode Reader::GetRawData3D() const { return impl_->GetRawData3D(); - }; + } VectorNode Reader::GetRawImages2D() const { return impl_->GetRawImages2D(); - }; + } bool Reader::ReadData3D( int64_t dataIndex, Data3D &data3DHeader ) const { return impl_->ReadData3D( dataIndex, data3DHeader ); } - bool Reader::GetData3DSizes( int64_t dataIndex, int64_t &rowMax, int64_t &columnMax, int64_t &pointsSize, - int64_t &groupsSize, int64_t &countSize, bool &bColumnIndex ) const + bool Reader::GetData3DSizes( int64_t dataIndex, int64_t &rowMax, int64_t &columnMax, + int64_t &pointsSize, int64_t &groupsSize, int64_t &countSize, + bool &bColumnIndex ) const { - return impl_->GetData3DSizes( dataIndex, rowMax, columnMax, pointsSize, groupsSize, countSize, bColumnIndex ); + return impl_->GetData3DSizes( dataIndex, rowMax, columnMax, pointsSize, groupsSize, countSize, + bColumnIndex ); } - bool Reader::ReadData3DGroupsData( int64_t dataIndex, int64_t groupCount, int64_t *idElementValue, + bool Reader::ReadData3DGroupsData( int64_t dataIndex, size_t groupCount, int64_t *idElementValue, int64_t *startPointIndex, int64_t *pointCount ) const { - return impl_->ReadData3DGroupsData( dataIndex, groupCount, idElementValue, startPointIndex, pointCount ); + return impl_->ReadData3DGroupsData( dataIndex, groupCount, idElementValue, startPointIndex, + pointCount ); } CompressedVectorReader Reader::SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData &buffers ) const + const Data3DPointsFloat &buffers ) const { return impl_->SetUpData3DPointsData( dataIndex, pointCount, buffers ); } CompressedVectorReader Reader::SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData_d &buffers ) const + const Data3DPointsDouble &buffers ) const { return impl_->SetUpData3DPointsData( dataIndex, pointCount, buffers ); } - } // end namespace e57 diff --git a/src/3rdParty/libE57Format/src/E57SimpleWriter.cpp b/src/3rdParty/libE57Format/src/E57SimpleWriter.cpp index c2c1fa7620978..b1fb28b6fdc55 100644 --- a/src/3rdParty/libE57Format/src/E57SimpleWriter.cpp +++ b/src/3rdParty/libE57Format/src/E57SimpleWriter.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) 2010 Stan Coleby (scoleby@intelisum.com) * Copyright (c) 2020 PTC Inc. + * Copyright (c) 2022 Andy Maloney * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by @@ -25,79 +26,272 @@ * DEALINGS IN THE SOFTWARE. */ +#include + #include "E57SimpleWriter.h" #include "WriterImpl.h" +namespace +{ + /// Fill in missing min/max data in the Data3D header for the following: + /// - cartesian points + /// - spherical points + /// - intensity + /// - time stamps + template + void _fillMinMaxData( e57::Data3D &ioData3DHeader, + const e57::Data3DPointsData_t &inBuffers ) + { + static_assert( std::is_floating_point::value, "Floating point type required." ); + + auto &pointFields = ioData3DHeader.pointFields; + + constexpr COORDTYPE cMin = std::numeric_limits::lowest(); + constexpr COORDTYPE cMax = std::numeric_limits::max(); + + // IF we are using scaled ints for cartesian points + // AND we haven't set either min or max + // THEN calculate them from the points + auto pointRangeMinimum = cMax; + auto pointRangeMaximum = cMin; + + const bool writePointRange = + ( pointFields.pointRangeNodeType == e57::NumericalNodeType::ScaledInteger ) && + ( pointFields.pointRangeMinimum == cMin ) && ( pointFields.pointRangeMaximum == cMax ); + + // IF we are using scaled ints for spherical angles + // AND we haven't set either min or max + // THEN calculate them from the points + auto angleMinimum = cMax; + auto angleMaximum = cMin; + + const bool writeAngle = + ( pointFields.angleNodeType == e57::NumericalNodeType::ScaledInteger ) && + ( pointFields.angleMinimum == cMin ) && ( pointFields.angleMaximum == cMax ); + + // IF we are using intensity + // AND we haven't set either min or max + // THEN calculate them from the points + double intensityMinimum = std::numeric_limits::max(); + double intensityMaximum = std::numeric_limits::lowest(); + + const bool writeIntensity = + pointFields.intensityField && ( ioData3DHeader.intensityLimits == e57::IntensityLimits{} ); + + // IF we are using scaled ints for timestamps + // AND we haven't set either min or max + // THEN calculate them from the points + double timeMinimum = std::numeric_limits::max(); + double timeMaximum = std::numeric_limits::lowest(); + + const bool writeTimeStamp = + pointFields.timeStampField && + ( pointFields.timeNodeType == e57::NumericalNodeType::ScaledInteger ) && + ( pointFields.timeMinimum == cMin ) && ( pointFields.timeMaximum == cMax ); + + // Now run through the points and set the things we need to + for ( size_t i = 0; i < ioData3DHeader.pointCount; ++i ) + { + if ( writePointRange && pointFields.cartesianXField ) + { + pointRangeMinimum = std::min( inBuffers.cartesianX[i], pointRangeMinimum ); + pointRangeMinimum = std::min( inBuffers.cartesianY[i], pointRangeMinimum ); + pointRangeMinimum = std::min( inBuffers.cartesianZ[i], pointRangeMinimum ); + + pointRangeMaximum = std::max( inBuffers.cartesianX[i], pointRangeMaximum ); + pointRangeMaximum = std::max( inBuffers.cartesianY[i], pointRangeMaximum ); + pointRangeMaximum = std::max( inBuffers.cartesianZ[i], pointRangeMaximum ); + } + + if ( writePointRange && pointFields.sphericalRangeField ) + { + // Note that the writer code uses pointRangeMinimum/pointRangeMaximum + // (see WriterImpl::NewData3D()) instead of using the sphericalBounds which has + // rangeMinimum and rangeMaximum. + pointRangeMinimum = std::min( inBuffers.sphericalRange[i], pointRangeMinimum ); + pointRangeMaximum = std::max( inBuffers.sphericalRange[i], pointRangeMaximum ); + } + + if ( writeAngle ) + { + angleMinimum = std::min( inBuffers.sphericalAzimuth[i], angleMinimum ); + angleMinimum = std::min( inBuffers.sphericalElevation[i], angleMinimum ); + + angleMaximum = std::max( inBuffers.sphericalAzimuth[i], angleMaximum ); + angleMaximum = std::max( inBuffers.sphericalElevation[i], angleMaximum ); + } + + if ( writeIntensity ) + { + intensityMinimum = std::min( inBuffers.intensity[i], intensityMinimum ); + intensityMaximum = std::max( inBuffers.intensity[i], intensityMaximum ); + } + + if ( writeTimeStamp ) + { + timeMinimum = std::min( inBuffers.timeStamp[i], timeMinimum ); + timeMaximum = std::max( inBuffers.timeStamp[i], timeMaximum ); + } + } + + if ( writePointRange ) + { + pointFields.pointRangeMinimum = pointRangeMinimum; + pointFields.pointRangeMaximum = pointRangeMaximum; + } + + if ( writeAngle ) + { + pointFields.angleMinimum = angleMinimum; + pointFields.angleMaximum = angleMaximum; + } + + if ( writeIntensity ) + { + ioData3DHeader.intensityLimits.intensityMinimum = intensityMinimum; + ioData3DHeader.intensityLimits.intensityMaximum = intensityMaximum; + } + + if ( writeTimeStamp ) + { + pointFields.timeMinimum = timeMinimum; + pointFields.timeMaximum = timeMaximum; + } + } + template void _fillMinMaxData( e57::Data3D &ioData3DHeader, + const e57::Data3DPointsFloat &inBuffers ); + template void _fillMinMaxData( e57::Data3D &ioData3DHeader, + const e57::Data3DPointsDouble &inBuffers ); +} + namespace e57 { + Writer::Writer( const ustring &filePath, const WriterOptions &options ) : + impl_( new WriterImpl( filePath, options ) ) + { + } - Writer::Writer( const ustring &filePath, const ustring &coordinateMetaData ) : - impl_( new WriterImpl( filePath, coordinateMetaData ) ) + // Note that this constructor is deprecated (see header). + Writer::Writer( const ustring &filePath, const ustring &coordinateMetadata ) : + Writer( filePath, WriterOptions{ {}, coordinateMetadata } ) { } bool Writer::IsOpen() const { return impl_->IsOpen(); - }; + } bool Writer::Close() { return impl_->Close(); - }; + } - ImageFile Writer::GetRawIMF() + int64_t Writer::WriteImage2DData( Image2D &image2DHeader, Image2DType imageType, + Image2DProjection imageProjection, int64_t startPos, + void *pBuffer, int64_t byteCount ) { - return impl_->GetRawIMF(); + auto *buffer = static_cast( pBuffer ); + const auto sizeInBytes = static_cast( byteCount ); + + const int64_t imageIndex = impl_->NewImage2D( image2DHeader ); + + const size_t written = impl_->WriteImage2DData( imageIndex, imageType, imageProjection, + buffer, startPos, sizeInBytes ); + + return static_cast( written ); } - StructureNode Writer::GetRawE57Root() + int64_t Writer::NewImage2D( Image2D &image2DHeader ) { - return impl_->GetRawE57Root(); - }; + return impl_->NewImage2D( image2DHeader ); + } - VectorNode Writer::GetRawData3D() + int64_t Writer::WriteImage2DData( int64_t imageIndex, Image2DType imageType, + Image2DProjection imageProjection, void *pBuffer, + int64_t start, int64_t count ) { - return impl_->GetRawData3D(); - }; + auto *buffer = static_cast( pBuffer ); + const auto size = static_cast( count ); - VectorNode Writer::GetRawImages2D() - { - return impl_->GetRawImages2D(); - }; + const size_t written = + impl_->WriteImage2DData( imageIndex, imageType, imageProjection, buffer, start, size ); - int64_t Writer::NewImage2D( Image2D &image2DHeader ) + return static_cast( written ); + } + + int64_t Writer::WriteData3DData( Data3D &data3DHeader, const Data3DPointsFloat &buffers ) { - return impl_->NewImage2D( image2DHeader ); - }; + _fillMinMaxData( data3DHeader, buffers ); + + const int64_t scanIndex = impl_->NewData3D( data3DHeader ); - int64_t Writer::WriteImage2DData( int64_t imageIndex, Image2DType imageType, Image2DProjection imageProjection, - void *pBuffer, int64_t start, int64_t count ) + e57::CompressedVectorWriter dataWriter = + impl_->SetUpData3DPointsData( scanIndex, data3DHeader.pointCount, buffers ); + + dataWriter.write( data3DHeader.pointCount ); + dataWriter.close(); + + return scanIndex; + } + + int64_t Writer::WriteData3DData( Data3D &data3DHeader, const Data3DPointsDouble &buffers ) { - return impl_->WriteImage2DData( imageIndex, imageType, imageProjection, pBuffer, start, count ); - }; + _fillMinMaxData( data3DHeader, buffers ); + + const int64_t scanIndex = impl_->NewData3D( data3DHeader ); + + e57::CompressedVectorWriter dataWriter = + impl_->SetUpData3DPointsData( scanIndex, data3DHeader.pointCount, buffers ); + + dataWriter.write( data3DHeader.pointCount ); + dataWriter.close(); + + return scanIndex; + } int64_t Writer::NewData3D( Data3D &data3DHeader ) { return impl_->NewData3D( data3DHeader ); - }; + } CompressedVectorWriter Writer::SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData &buffers ) + const Data3DPointsFloat &buffers ) { return impl_->SetUpData3DPointsData( dataIndex, pointCount, buffers ); } CompressedVectorWriter Writer::SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData_d &buffers ) + const Data3DPointsDouble &buffers ) { return impl_->SetUpData3DPointsData( dataIndex, pointCount, buffers ); } - bool Writer::WriteData3DGroupsData( int64_t dataIndex, int64_t groupCount, int64_t *idElementValue, - int64_t *startPointIndex, int64_t *pointCount ) + bool Writer::WriteData3DGroupsData( int64_t dataIndex, size_t groupCount, + int64_t *idElementValue, int64_t *startPointIndex, + int64_t *pointCount ) { - return impl_->WriteData3DGroupsData( dataIndex, groupCount, idElementValue, startPointIndex, pointCount ); + return impl_->WriteData3DGroupsData( dataIndex, groupCount, idElementValue, startPointIndex, + pointCount ); } + ImageFile Writer::GetRawIMF() + { + return impl_->GetRawIMF(); + } + + StructureNode Writer::GetRawE57Root() + { + return impl_->GetRawE57Root(); + } + + VectorNode Writer::GetRawData3D() + { + return impl_->GetRawData3D(); + } + + VectorNode Writer::GetRawImages2D() + { + return impl_->GetRawImages2D(); + } } // end namespace e57 diff --git a/src/3rdParty/libE57Format/src/E57Version.cpp b/src/3rdParty/libE57Format/src/E57Version.cpp new file mode 100644 index 0000000000000..b768c14e412ab --- /dev/null +++ b/src/3rdParty/libE57Format/src/E57Version.cpp @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: MIT +// Copyright 2020 Andy Maloney + +#include + +#include "ASTMVersion.h" +#include "E57Version.h" + +namespace e57 +{ + // REVISION_ID should be passed from compiler command line +#ifndef REVISION_ID +#error "Need to specify REVISION_ID on command line" +#endif + + std::string Version::astm() + { + std::ostringstream stringStream; + stringStream << E57_FORMAT_MAJOR << "." << E57_FORMAT_MINOR; + return stringStream.str(); + } + + uint32_t Version::astmMajor() + { + return E57_FORMAT_MAJOR; + } + + uint32_t Version::astmMinor() + { + return E57_FORMAT_MINOR; + } + + std::string Version::library() + { + return REVISION_ID; + } + + void Version::get( uint32_t &astmMajor, uint32_t &astmMinor, std::string &libraryId ) + { + astmMajor = E57_FORMAT_MAJOR; + astmMinor = E57_FORMAT_MINOR; + libraryId = REVISION_ID; + } + + namespace Utilities + { + void getVersions( int &astmMajor, int &astmMinor, std::string &libraryId ) + { + astmMajor = E57_FORMAT_MAJOR; + astmMinor = E57_FORMAT_MINOR; + libraryId = REVISION_ID; + } + } + +} diff --git a/src/3rdParty/libE57Format/src/E57Version.h b/src/3rdParty/libE57Format/src/E57Version.h deleted file mode 100644 index 925b2cbd121ae..0000000000000 --- a/src/3rdParty/libE57Format/src/E57Version.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once -// SPDX-License-Identifier: MIT -// Copyright 2020 Andy Maloney - -#include - -namespace e57 -{ - /// Version numbers of ASTM standard that this library supports - constexpr uint32_t E57_FORMAT_MAJOR = 1; - constexpr uint32_t E57_FORMAT_MINOR = 0; -} diff --git a/src/3rdParty/libE57Format/src/E57XmlParser.cpp b/src/3rdParty/libE57Format/src/E57XmlParser.cpp index eecc2ea289589..3908823265321 100644 --- a/src/3rdParty/libE57Format/src/E57XmlParser.cpp +++ b/src/3rdParty/libE57Format/src/E57XmlParser.cpp @@ -1,919 +1,950 @@ -/* - * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) - * Modified work Copyright 2018 - 2020 Andy Maloney - * - * Permission is hereby granted, free of charge, to any person or organization - * obtaining a copy of the software and accompanying documentation covered by - * this license (the "Software") to use, reproduce, display, distribute, - * execute, and transmit the Software, and to prepare derivative works of the - * Software, and to permit third-parties to whom the Software is furnished to - * do so, all subject to the following: - * - * The copyright notices in the Software and this entire statement, including - * the above license grant, this restriction and the following disclaimer, - * must be included in all copies of the Software, in whole or in part, and - * all derivative works of the Software, unless such copies or derivative - * works are solely in the form of machine-executable object code generated by - * a source language processor. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT - * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE - * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - */ - -#include -#include - -#include -#include - -#include "BlobNodeImpl.h" -#include "CheckedFile.h" -#include "CompressedVectorNodeImpl.h" -#include "E57XmlParser.h" -#include "FloatNodeImpl.h" -#include "ImageFileImpl.h" -#include "IntegerNodeImpl.h" -#include "ScaledIntegerNodeImpl.h" -#include "StringNodeImpl.h" -#include "VectorNodeImpl.h" - -#if __GNUC__ >= 11 -#include -#endif - -using namespace e57; -using namespace XERCES_CPP_NAMESPACE; - -// define convenient constants for the attribute names -static const XMLCh att_minimum[] = { - chLatin_m, chLatin_i, chLatin_n, chLatin_i, chLatin_m, chLatin_u, chLatin_m, chNull -}; -static const XMLCh att_maximum[] = { - chLatin_m, chLatin_a, chLatin_x, chLatin_i, chLatin_m, chLatin_u, chLatin_m, chNull -}; -static const XMLCh att_scale[] = { chLatin_s, chLatin_c, chLatin_a, chLatin_l, chLatin_e, chNull }; -static const XMLCh att_offset[] = { chLatin_o, chLatin_f, chLatin_f, chLatin_s, chLatin_e, chLatin_t, chNull }; -static const XMLCh att_precision[] = { chLatin_p, chLatin_r, chLatin_e, chLatin_c, chLatin_i, - chLatin_s, chLatin_i, chLatin_o, chLatin_n, chNull }; -static const XMLCh att_allowHeterogeneousChildren[] = { - chLatin_a, chLatin_l, chLatin_l, chLatin_o, chLatin_w, chLatin_H, chLatin_e, chLatin_t, chLatin_e, - chLatin_r, chLatin_o, chLatin_g, chLatin_e, chLatin_n, chLatin_e, chLatin_o, chLatin_u, chLatin_s, - chLatin_C, chLatin_h, chLatin_i, chLatin_l, chLatin_d, chLatin_r, chLatin_e, chLatin_n, chNull -}; -static const XMLCh att_fileOffset[] = { chLatin_f, chLatin_i, chLatin_l, chLatin_e, chLatin_O, chLatin_f, - chLatin_f, chLatin_s, chLatin_e, chLatin_t, chNull }; - -static const XMLCh att_type[] = { chLatin_t, chLatin_y, chLatin_p, chLatin_e, chNull }; -static const XMLCh att_length[] = { chLatin_l, chLatin_e, chLatin_n, chLatin_g, chLatin_t, chLatin_h, chNull }; -static const XMLCh att_recordCount[] = { chLatin_r, chLatin_e, chLatin_c, chLatin_o, chLatin_r, chLatin_d, - chLatin_C, chLatin_o, chLatin_u, chLatin_n, chLatin_t, chNull }; - -inline int64_t convertStrToLL( const std::string &inStr ) -{ -#if defined( _MSC_VER ) - return _atoi64( inStr.c_str() ); -#elif defined( __GNUC__ ) - return strtoll( inStr.c_str(), nullptr, 10 ); -#else -#error "Need to define string to long long conversion for this compiler" -#endif -} - -//============================================================================= -// E57FileInputStream - -class E57FileInputStream : public BinInputStream -{ -public: - E57FileInputStream( CheckedFile *cf, uint64_t logicalStart, uint64_t logicalLength ); - ~E57FileInputStream() override = default; - - E57FileInputStream( const E57FileInputStream & ) = delete; - E57FileInputStream &operator=( const E57FileInputStream & ) = delete; - - XMLFilePos curPos() const override - { - return ( logicalPosition_ ); - } - XMLSize_t readBytes( XMLByte *const toFill, const XMLSize_t maxToRead ) override; - const XMLCh *getContentType() const override - { - return nullptr; - } - -private: - //??? lifetime of cf_ must be longer than this object! - CheckedFile *cf_; - uint64_t logicalStart_; - uint64_t logicalLength_; - uint64_t logicalPosition_; -}; - -E57FileInputStream::E57FileInputStream( CheckedFile *cf, uint64_t logicalStart, uint64_t logicalLength ) : - cf_( cf ), logicalStart_( logicalStart ), logicalLength_( logicalLength ), logicalPosition_( logicalStart ) -{ -} - -XMLSize_t E57FileInputStream::readBytes( XMLByte *const toFill, const XMLSize_t maxToRead ) -{ - if ( logicalPosition_ > logicalStart_ + logicalLength_ ) - { - return ( 0 ); - } - - int64_t available = logicalStart_ + logicalLength_ - logicalPosition_; - if ( available <= 0 ) - { - return ( 0 ); - } - - /// size_t and XMLSize_t should be compatible, should get compiler warning - /// here if not - size_t maxToRead_size = maxToRead; - - /// Be careful if size_t is smaller than int64_t - size_t available_size; - if ( sizeof( size_t ) >= sizeof( int64_t ) ) - { - /// size_t is at least as big as int64_t - available_size = static_cast( available ); - } - else - { - /// size_t is smaller than int64_t, Calc max that size_t can hold - const int64_t size_max = std::numeric_limits::max(); - - /// read smaller of size_max, available - ///??? redo - if ( size_max < available ) - { - available_size = static_cast( size_max ); - } - else - { - available_size = static_cast( available ); - } - } - - size_t readCount = std::min( maxToRead_size, available_size ); - - cf_->seek( logicalPosition_ ); - cf_->read( reinterpret_cast( toFill ), readCount ); //??? cast ok? - logicalPosition_ += readCount; - return ( readCount ); -} - -//============================================================================= -// E57XmlFileInputSource - -E57XmlFileInputSource::E57XmlFileInputSource( CheckedFile *cf, uint64_t logicalStart, uint64_t logicalLength ) : - InputSource( "E57File", - XMLPlatformUtils::fgMemoryManager ), //??? what if want to use our own - // memory - // manager?, what bufid is good? - cf_( cf ), logicalStart_( logicalStart ), logicalLength_( logicalLength ) -{ -} - -BinInputStream *E57XmlFileInputSource::makeStream() const -{ - return new E57FileInputStream( cf_, logicalStart_, logicalLength_ ); -} - -//============================================================================= -// E57XmlParser::ParseInfo - -E57XmlParser::ParseInfo::ParseInfo() : - nodeType( static_cast( 0 ) ), minimum( 0 ), maximum( 0 ), scale( 0 ), offset( 0 ), - precision( static_cast( 0 ) ), floatMinimum( 0 ), floatMaximum( 0 ), fileOffset( 0 ), length( 0 ), - allowHeterogeneousChildren( false ), recordCount( 0 ) -{ -} - -void E57XmlParser::ParseInfo::dump( int indent, std::ostream &os ) const -{ - os << space( indent ) << "nodeType: " << nodeType << std::endl; - os << space( indent ) << "minimum: " << minimum << std::endl; - os << space( indent ) << "maximum: " << maximum << std::endl; - os << space( indent ) << "scale: " << scale << std::endl; - os << space( indent ) << "offset: " << offset << std::endl; - os << space( indent ) << "precision: " << precision << std::endl; - os << space( indent ) << "floatMinimum: " << floatMinimum << std::endl; - os << space( indent ) << "floatMaximum: " << floatMaximum << std::endl; - os << space( indent ) << "fileOffset: " << fileOffset << std::endl; - os << space( indent ) << "length: " << length << std::endl; - os << space( indent ) << "allowHeterogeneousChildren: " << allowHeterogeneousChildren << std::endl; - os << space( indent ) << "recordCount: " << recordCount << std::endl; - if ( container_ni ) - { - os << space( indent ) << "container_ni: " << std::endl; - } - else - { - os << space( indent ) << "container_ni: " << std::endl; - } - os << space( indent ) << "childText: \"" << childText << "\"" << std::endl; -} - -//============================================================================= -// E57XmlParser - -E57XmlParser::E57XmlParser( ImageFileImplSharedPtr imf ) : imf_( imf ), xmlReader( nullptr ) -{ -} - -E57XmlParser::~E57XmlParser() -{ - delete xmlReader; - - xmlReader = nullptr; - - XMLPlatformUtils::Terminate(); -} - -void E57XmlParser::init() -{ - // Initialize the XML4C2 system - try - { - XMLPlatformUtils::Initialize(); - } - catch ( const XMLException &ex ) - { - /// Turn parser exception into E57Exception - throw E57_EXCEPTION2( E57_ERROR_XML_PARSER_INIT, - "parserMessage=" + ustring( XMLString::transcode( ex.getMessage() ) ) ); - } - - xmlReader = XMLReaderFactory::createXMLReader(); //??? auto_ptr? - - if ( !xmlReader ) - { - throw E57_EXCEPTION2( E57_ERROR_XML_PARSER_INIT, "could not create the xml reader" ); - } - - //??? check these are right - xmlReader->setFeature( XMLUni::fgSAX2CoreValidation, true ); - xmlReader->setFeature( XMLUni::fgXercesDynamic, true ); - xmlReader->setFeature( XMLUni::fgSAX2CoreNameSpaces, true ); - xmlReader->setFeature( XMLUni::fgXercesSchema, true ); - xmlReader->setFeature( XMLUni::fgXercesSchemaFullChecking, true ); - xmlReader->setFeature( XMLUni::fgSAX2CoreNameSpacePrefixes, true ); - - xmlReader->setContentHandler( this ); - xmlReader->setErrorHandler( this ); -} - -void E57XmlParser::parse( InputSource &inputSource ) -{ - xmlReader->parse( inputSource ); -} - -void E57XmlParser::startElement( const XMLCh *const uri, const XMLCh *const localName, const XMLCh *const qName, - const Attributes &attributes ) -{ -#ifdef E57_MAX_VERBOSE - std::cout << "startElement" << std::endl; - std::cout << space( 2 ) << "URI: " << toUString( uri ) << std::endl; - std::cout << space( 2 ) << "localName: " << toUString( localName ) << std::endl; - std::cout << space( 2 ) << "qName: " << toUString( qName ) << std::endl; - - for ( size_t i = 0; i < attributes.getLength(); i++ ) - { - std::cout << space( 2 ) << "Attribute[" << i << "]" << std::endl; - std::cout << space( 4 ) << "URI: " << toUString( attributes.getURI( i ) ) << std::endl; - std::cout << space( 4 ) << "localName: " << toUString( attributes.getLocalName( i ) ) << std::endl; - std::cout << space( 4 ) << "qName: " << toUString( attributes.getQName( i ) ) << std::endl; - std::cout << space( 4 ) << "value: " << toUString( attributes.getValue( i ) ) << std::endl; - } -#endif - /// Get Type attribute - ustring node_type = lookupAttribute( attributes, att_type ); - - //??? check to make sure not in primitive type (can only nest inside compound - // types). - - ParseInfo pi; - - if ( node_type == "Integer" ) - { -#ifdef E57_MAX_VERBOSE - std::cout << "got a Integer" << std::endl; -#endif - //??? check validity of numeric strings - pi.nodeType = E57_INTEGER; - - if ( isAttributeDefined( attributes, att_minimum ) ) - { - ustring minimum_str = lookupAttribute( attributes, att_minimum ); - - pi.minimum = convertStrToLL( minimum_str ); - } - else - { - /// Not defined defined in XML, so defaults to E57_INT64_MIN - pi.minimum = E57_INT64_MIN; - } - - if ( isAttributeDefined( attributes, att_maximum ) ) - { - ustring maximum_str = lookupAttribute( attributes, att_maximum ); - - pi.maximum = convertStrToLL( maximum_str ); - } - else - { - /// Not defined defined in XML, so defaults to E57_INT64_MAX - pi.maximum = E57_INT64_MAX; - } - - /// Push info so far onto stack - stack_.push( pi ); - } - else if ( node_type == "ScaledInteger" ) - { -#ifdef E57_MAX_VERBOSE - std::cout << "got a ScaledInteger" << std::endl; -#endif - pi.nodeType = E57_SCALED_INTEGER; - - //??? check validity of numeric strings - if ( isAttributeDefined( attributes, att_minimum ) ) - { - ustring minimum_str = lookupAttribute( attributes, att_minimum ); - - pi.minimum = convertStrToLL( minimum_str ); - } - else - { - /// Not defined defined in XML, so defaults to E57_INT64_MIN - pi.minimum = E57_INT64_MIN; - } - - if ( isAttributeDefined( attributes, att_maximum ) ) - { - ustring maximum_str = lookupAttribute( attributes, att_maximum ); - - pi.maximum = convertStrToLL( maximum_str ); - } - else - { - /// Not defined defined in XML, so defaults to E57_INT64_MAX - pi.maximum = E57_INT64_MAX; - } - - if ( isAttributeDefined( attributes, att_scale ) ) - { - ustring scale_str = lookupAttribute( attributes, att_scale ); - pi.scale = atof( scale_str.c_str() ); //??? use exact rounding library - } - else - { - /// Not defined defined in XML, so defaults to 1.0 - pi.scale = 1.0; - } - - if ( isAttributeDefined( attributes, att_offset ) ) - { - ustring offset_str = lookupAttribute( attributes, att_offset ); - pi.offset = atof( offset_str.c_str() ); //??? use exact rounding library - } - else - { - /// Not defined defined in XML, so defaults to 0.0 - pi.offset = 0.0; - } - - /// Push info so far onto stack - stack_.push( pi ); - } - else if ( node_type == "Float" ) - { -#ifdef E57_MAX_VERBOSE - std::cout << "got a Float" << std::endl; -#endif - pi.nodeType = E57_FLOAT; - - if ( isAttributeDefined( attributes, att_precision ) ) - { - ustring precision_str = lookupAttribute( attributes, att_precision ); - if ( precision_str == "single" ) - { - pi.precision = E57_SINGLE; - } - else if ( precision_str == "double" ) - { - pi.precision = E57_DOUBLE; - } - else - { - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, - "precisionString=" + precision_str + " fileName=" + imf_->fileName() + - " uri=" + toUString( uri ) + " localName=" + toUString( localName ) + - " qName=" + toUString( qName ) ); - } - } - else - { - /// Not defined defined in XML, so defaults to double - pi.precision = E57_DOUBLE; - } - - if ( isAttributeDefined( attributes, att_minimum ) ) - { - ustring minimum_str = lookupAttribute( attributes, att_minimum ); - pi.floatMinimum = atof( minimum_str.c_str() ); //??? use exact rounding library - } - else - { - /// Not defined defined in XML, so defaults to E57_FLOAT_MIN or - /// E57_DOUBLE_MIN - if ( pi.precision == E57_SINGLE ) - { - pi.floatMinimum = E57_FLOAT_MIN; - } - else - { - pi.floatMinimum = E57_DOUBLE_MIN; - } - } - - if ( isAttributeDefined( attributes, att_maximum ) ) - { - ustring maximum_str = lookupAttribute( attributes, att_maximum ); - pi.floatMaximum = atof( maximum_str.c_str() ); //??? use exact rounding library - } - else - { - /// Not defined defined in XML, so defaults to FLOAT_MAX or DOUBLE_MAX - if ( pi.precision == E57_SINGLE ) - { - pi.floatMaximum = E57_FLOAT_MAX; - } - else - { - pi.floatMaximum = E57_DOUBLE_MAX; - } - } - - /// Push info so far onto stack - stack_.push( pi ); - } - else if ( node_type == "String" ) - { -#ifdef E57_MAX_VERBOSE - std::cout << "got a String" << std::endl; -#endif - pi.nodeType = E57_STRING; - - /// Push info so far onto stack - stack_.push( pi ); - } - else if ( node_type == "Blob" ) - { -#ifdef E57_MAX_VERBOSE - std::cout << "got a Blob" << std::endl; -#endif - pi.nodeType = E57_BLOB; - - //??? check validity of numeric strings - - /// fileOffset is required to be defined - ustring fileOffset_str = lookupAttribute( attributes, att_fileOffset ); - - pi.fileOffset = convertStrToLL( fileOffset_str ); - - /// length is required to be defined - ustring length_str = lookupAttribute( attributes, att_length ); - - pi.length = convertStrToLL( length_str ); - - /// Push info so far onto stack - stack_.push( pi ); - } - else if ( node_type == "Structure" ) - { -#ifdef E57_MAX_VERBOSE - std::cout << "got a Structure" << std::endl; -#endif - pi.nodeType = E57_STRUCTURE; - - /// Read name space decls, if e57Root element - if ( toUString( localName ) == "e57Root" ) - { - /// Search attributes for namespace declarations (only allowed in - /// E57Root structure) - bool gotDefault = false; - for ( size_t i = 0; i < attributes.getLength(); i++ ) - { - /// Check if declaring the default namespace - if ( toUString( attributes.getQName( i ) ) == "xmlns" ) - { -#ifdef E57_VERBOSE - std::cout << "declared default namespace, URI=" << toUString( attributes.getValue( i ) ) << std::endl; -#endif - imf_->extensionsAdd( "", toUString( attributes.getValue( i ) ) ); - gotDefault = true; - } - - /// Check if declaring a namespace - if ( toUString( attributes.getURI( i ) ) == "http://www.w3.org/2000/xmlns/" ) - { -#ifdef E57_VERBOSE - std::cout << "declared extension, prefix=" << toUString( attributes.getLocalName( i ) ) - << " URI=" << toUString( attributes.getValue( i ) ) << std::endl; -#endif - imf_->extensionsAdd( toUString( attributes.getLocalName( i ) ), toUString( attributes.getValue( i ) ) ); - } - } - - /// If didn't declare a default namespace, have error - if ( !gotDefault ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, - "fileName=" + imf_->fileName() + " uri=" + toUString( uri ) + - " localName=" + toUString( localName ) + " qName=" + toUString( qName ) ); - } - } - - /// Create container now, so can hold children - std::shared_ptr s_ni( new StructureNodeImpl( imf_ ) ); - pi.container_ni = s_ni; - - /// After have Structure, check again if E57Root, if so mark attached so - /// all children will be attached when added - if ( toUString( localName ) == "e57Root" ) - { - s_ni->setAttachedRecursive(); - } - - /// Push info so far onto stack - stack_.push( pi ); - } - else if ( node_type == "Vector" ) - { -#ifdef E57_MAX_VERBOSE - std::cout << "got a Vector" << std::endl; -#endif - pi.nodeType = E57_VECTOR; - - if ( isAttributeDefined( attributes, att_allowHeterogeneousChildren ) ) - { - ustring allowHetero_str = lookupAttribute( attributes, att_allowHeterogeneousChildren ); - - int64_t i64 = convertStrToLL( allowHetero_str ); - - if ( i64 == 0 ) - { - pi.allowHeterogeneousChildren = false; - } - else if ( i64 == 1 ) - { - pi.allowHeterogeneousChildren = true; - } - else - { - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, - "allowHeterogeneousChildren=" + toString( i64 ) + "fileName=" + imf_->fileName() + - " uri=" + toUString( uri ) + " localName=" + toUString( localName ) + - " qName=" + toUString( qName ) ); - } - } - else - { - /// Not defined defined in XML, so defaults to false - pi.allowHeterogeneousChildren = false; - } - - /// Create container now, so can hold children - std::shared_ptr v_ni( new VectorNodeImpl( imf_, pi.allowHeterogeneousChildren ) ); - pi.container_ni = v_ni; - - /// Push info so far onto stack - stack_.push( pi ); - } - else if ( node_type == "CompressedVector" ) - { -#ifdef E57_MAX_VERBOSE - std::cout << "got a CompressedVector" << std::endl; -#endif - pi.nodeType = E57_COMPRESSED_VECTOR; - - /// fileOffset is required to be defined - ustring fileOffset_str = lookupAttribute( attributes, att_fileOffset ); - - pi.fileOffset = convertStrToLL( fileOffset_str ); - - /// recordCount is required to be defined - ustring recordCount_str = lookupAttribute( attributes, att_recordCount ); - - pi.recordCount = convertStrToLL( recordCount_str ); - - /// Create container now, so can hold children - std::shared_ptr cv_ni( new CompressedVectorNodeImpl( imf_ ) ); - cv_ni->setRecordCount( pi.recordCount ); - cv_ni->setBinarySectionLogicalStart( - imf_->file_->physicalToLogical( pi.fileOffset ) ); //??? what if file_ is NULL? - pi.container_ni = cv_ni; - - /// Push info so far onto stack - stack_.push( pi ); - } - else - { - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, - "nodeType=" + node_type + " fileName=" + imf_->fileName() + " uri=" + toUString( uri ) + - " localName=" + toUString( localName ) + " qName=" + toUString( qName ) ); - } -#ifdef E57_MAX_VERBOSE - pi.dump( 4 ); -#endif -} - -void E57XmlParser::endElement( const XMLCh *const uri, const XMLCh *const localName, const XMLCh *const qName ) -{ -#ifdef E57_MAX_VERBOSE - std::cout << "endElement" << std::endl; -#endif - - /// Pop the node that just ended - ParseInfo pi = stack_.top(); //??? really want to make a copy here? - stack_.pop(); -#ifdef E57_MAX_VERBOSE - pi.dump( 4 ); -#endif - - /// We should now have all the info we need to create the node - NodeImplSharedPtr current_ni; - - switch ( pi.nodeType ) - { - case E57_STRUCTURE: - case E57_VECTOR: - current_ni = pi.container_ni; - break; - case E57_COMPRESSED_VECTOR: - { - /// Verify that both prototype and codecs child elements were defined - /// ??? - current_ni = pi.container_ni; - } - break; - case E57_INTEGER: - { - /// Convert child text (if any) to value, else default to 0.0 - int64_t intValue; - if ( pi.childText.length() > 0 ) - { - intValue = convertStrToLL( pi.childText ); - } - else - { - intValue = 0; - } - std::shared_ptr i_ni( new IntegerNodeImpl( imf_, intValue, pi.minimum, pi.maximum ) ); - current_ni = i_ni; - } - break; - case E57_SCALED_INTEGER: - { - /// Convert child text (if any) to value, else default to 0.0 - int64_t intValue; - if ( pi.childText.length() > 0 ) - { - intValue = convertStrToLL( pi.childText ); - } - else - { - intValue = 0; - } - std::shared_ptr si_ni( - new ScaledIntegerNodeImpl( imf_, intValue, pi.minimum, pi.maximum, pi.scale, pi.offset ) ); - current_ni = si_ni; - } - break; - case E57_FLOAT: - { - /// Convert child text (if any) to value, else default to 0.0 - double floatValue; - if ( pi.childText.length() > 0 ) - { - floatValue = atof( pi.childText.c_str() ); - } - else - { - floatValue = 0.0; - } - std::shared_ptr f_ni( - new FloatNodeImpl( imf_, floatValue, pi.precision, pi.floatMinimum, pi.floatMaximum ) ); - current_ni = f_ni; - } - break; - case E57_STRING: - { - std::shared_ptr s_ni( new StringNodeImpl( imf_, pi.childText ) ); - current_ni = s_ni; - } - break; - case E57_BLOB: - { - std::shared_ptr b_ni( new BlobNodeImpl( imf_, pi.fileOffset, pi.length ) ); - current_ni = b_ni; - } - break; - default: - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "nodeType=" + toString( pi.nodeType ) + - " fileName=" + imf_->fileName() + " uri=" + toUString( uri ) + - " localName=" + toUString( localName ) + - " qName=" + toUString( qName ) ); - } -#ifdef E57_MAX_VERBOSE - current_ni->dump( 4 ); -#endif - - /// If first node in file ended, we are all done - if ( stack_.empty() ) - { - /// Top level should be Structure - if ( current_ni->type() != E57_STRUCTURE ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, - "currentType=" + toString( current_ni->type() ) + " fileName=" + imf_->fileName() + - " uri=" + toUString( uri ) + " localName=" + toUString( localName ) + - " qName=" + toUString( qName ) ); - } - imf_->root_ = std::static_pointer_cast( current_ni ); - return; - } - - /// Get next level up node (when entered function), which should be a - /// container. - NodeImplSharedPtr parent_ni = stack_.top().container_ni; - - if ( !parent_ni ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, "fileName=" + imf_->fileName() + " uri=" + toUString( uri ) + - " localName=" + toUString( localName ) + - " qName=" + toUString( qName ) ); - } - - /// Add current node into parent at top of stack - switch ( parent_ni->type() ) - { - case E57_STRUCTURE: - { - std::shared_ptr struct_ni = std::static_pointer_cast( parent_ni ); - - /// Add named child to structure - struct_ni->set( toUString( qName ), current_ni ); - } - break; - case E57_VECTOR: - { - std::shared_ptr vector_ni = std::static_pointer_cast( parent_ni ); - - /// Add unnamed child to vector - vector_ni->append( current_ni ); - } - break; - case E57_COMPRESSED_VECTOR: - { - std::shared_ptr cv_ni = - std::static_pointer_cast( parent_ni ); - ustring uQName = toUString( qName ); - - /// n can be either prototype or codecs - if ( uQName == "prototype" ) - { - cv_ni->setPrototype( current_ni ); - } - else if ( uQName == "codecs" ) - { - if ( current_ni->type() != E57_VECTOR ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, - "currentType=" + toString( current_ni->type() ) + " fileName=" + imf_->fileName() + - " uri=" + toUString( uri ) + " localName=" + toUString( localName ) + - " qName=" + toUString( qName ) ); - } - std::shared_ptr vi = std::static_pointer_cast( current_ni ); - - /// Check VectorNode is hetero - if ( !vi->allowHeteroChildren() ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, - "currentType=" + toString( current_ni->type() ) + " fileName=" + imf_->fileName() + - " uri=" + toUString( uri ) + " localName=" + toUString( localName ) + - " qName=" + toUString( qName ) ); - } - - cv_ni->setCodecs( vi ); - } - else - { - /// Found unknown XML child element of CompressedVector, not - /// prototype or codecs - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, - +"fileName=" + imf_->fileName() + " uri=" + toUString( uri ) + - " localName=" + toUString( localName ) + " qName=" + toUString( qName ) ); - } - } - break; - default: - /// Have bad XML nesting, parent should have been a container. - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, - "parentType=" + toString( parent_ni->type() ) + " fileName=" + imf_->fileName() + - " uri=" + toUString( uri ) + " localName=" + toUString( localName ) + - " qName=" + toUString( qName ) ); - } -} - -void E57XmlParser::characters( const XMLCh *const chars, const XMLSize_t length ) -{ - (void)length; -//??? use length to make ustring -#ifdef E57_MAX_VERBOSE - std::cout << "characters, chars=\"" << toUString( chars ) << "\" length=" << length << std::endl; -#endif - /// Get active element - ParseInfo &pi = stack_.top(); - - /// Check if child text is allowed for current E57 element type - switch ( pi.nodeType ) - { - case E57_STRUCTURE: - case E57_VECTOR: - case E57_COMPRESSED_VECTOR: - case E57_BLOB: - { - /// If characters aren't whitespace, have an error, else ignore - ustring s = toUString( chars ); - if ( s.find_first_not_of( " \t\n\r" ) != std::string::npos ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, "chars=" + toUString( chars ) ); - } - } - break; - default: - /// Append to any previous characters - pi.childText += toUString( chars ); - } -} - -void E57XmlParser::error( const SAXParseException &ex ) -{ - throw E57_EXCEPTION2( E57_ERROR_XML_PARSER, "systemId=" + ustring( XMLString::transcode( ex.getSystemId() ) ) + - " xmlLine=" + toString( ex.getLineNumber() ) + - " xmlColumn=" + toString( ex.getColumnNumber() ) + " parserMessage=" + - ustring( XMLString::transcode( ex.getMessage() ) ) ); -} - -void E57XmlParser::fatalError( const SAXParseException &ex ) -{ - throw E57_EXCEPTION2( E57_ERROR_XML_PARSER, "systemId=" + ustring( XMLString::transcode( ex.getSystemId() ) ) + - " xmlLine=" + toString( ex.getLineNumber() ) + - " xmlColumn=" + toString( ex.getColumnNumber() ) + " parserMessage=" + - ustring( XMLString::transcode( ex.getMessage() ) ) ); -} - -void E57XmlParser::warning( const SAXParseException &ex ) -{ - /// Don't take any action on warning from parser, just report - std::cerr << "**** XML parser warning: " << ustring( XMLString::transcode( ex.getMessage() ) ) << std::endl; - std::cerr << " Debug info:" << std::endl; - std::cerr << " systemId=" << XMLString::transcode( ex.getSystemId() ) << std::endl; - std::cerr << ", xmlLine=" << ex.getLineNumber() << std::endl; - std::cerr << ", xmlColumn=" << ex.getColumnNumber() << std::endl; -} - -ustring E57XmlParser::toUString( const XMLCh *const xml_str ) -{ - ustring u_str; - if ( xml_str && *xml_str ) - { - TranscodeToStr UTF8Transcoder( xml_str, "UTF-8" ); - u_str = ustring( reinterpret_cast( UTF8Transcoder.str() ) ); - } - return ( u_str ); -} - -ustring E57XmlParser::lookupAttribute( const Attributes &attributes, const XMLCh *attribute_name ) -{ - XMLSize_t attr_index; - if ( !attributes.getIndex( attribute_name, attr_index ) ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_XML_FORMAT, "attributeName=" + toUString( attribute_name ) ); - } - return ( toUString( attributes.getValue( attr_index ) ) ); -} - -bool E57XmlParser::isAttributeDefined( const Attributes &attributes, const XMLCh *attribute_name ) -{ - XMLSize_t attr_index; - return ( attributes.getIndex( attribute_name, attr_index ) ); -} +/* + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#include +#include +#include + +#include +#include + +#include +#include + +#include "BlobNodeImpl.h" +#include "CheckedFile.h" +#include "CompressedVectorNodeImpl.h" +#include "E57XmlParser.h" +#include "FloatNodeImpl.h" +#include "ImageFileImpl.h" +#include "IntegerNodeImpl.h" +#include "ScaledIntegerNodeImpl.h" +#include "StringFunctions.h" +#include "StringNodeImpl.h" +#include "VectorNodeImpl.h" + +using namespace e57; +using namespace XERCES_CPP_NAMESPACE; + +// define convenient constants for the attribute names +static const XMLCh att_minimum[] = { chLatin_m, chLatin_i, chLatin_n, chLatin_i, + chLatin_m, chLatin_u, chLatin_m, chNull }; +static const XMLCh att_maximum[] = { chLatin_m, chLatin_a, chLatin_x, chLatin_i, + chLatin_m, chLatin_u, chLatin_m, chNull }; +static const XMLCh att_scale[] = { chLatin_s, chLatin_c, chLatin_a, chLatin_l, chLatin_e, chNull }; +static const XMLCh att_offset[] = { chLatin_o, chLatin_f, chLatin_f, chLatin_s, + chLatin_e, chLatin_t, chNull }; +static const XMLCh att_precision[] = { chLatin_p, chLatin_r, chLatin_e, chLatin_c, chLatin_i, + chLatin_s, chLatin_i, chLatin_o, chLatin_n, chNull }; +static const XMLCh att_allowHeterogeneousChildren[] = { + chLatin_a, chLatin_l, chLatin_l, chLatin_o, chLatin_w, chLatin_H, chLatin_e, + chLatin_t, chLatin_e, chLatin_r, chLatin_o, chLatin_g, chLatin_e, chLatin_n, + chLatin_e, chLatin_o, chLatin_u, chLatin_s, chLatin_C, chLatin_h, chLatin_i, + chLatin_l, chLatin_d, chLatin_r, chLatin_e, chLatin_n, chNull +}; +static const XMLCh att_fileOffset[] = { chLatin_f, chLatin_i, chLatin_l, chLatin_e, + chLatin_O, chLatin_f, chLatin_f, chLatin_s, + chLatin_e, chLatin_t, chNull }; + +static const XMLCh att_type[] = { chLatin_t, chLatin_y, chLatin_p, chLatin_e, chNull }; +static const XMLCh att_length[] = { chLatin_l, chLatin_e, chLatin_n, chLatin_g, + chLatin_t, chLatin_h, chNull }; +static const XMLCh att_recordCount[] = { chLatin_r, chLatin_e, chLatin_c, chLatin_o, + chLatin_r, chLatin_d, chLatin_C, chLatin_o, + chLatin_u, chLatin_n, chLatin_t, chNull }; + +static_assert( std::is_same::value, + "size_t and XMLSize_t should be the same type" ); + +namespace +{ + inline int64_t convertStrToLL( const std::string &inStr ) + { +#if defined( _MSC_VER ) + return _atoi64( inStr.c_str() ); +#elif defined( __GNUC__ ) + return strtoll( inStr.c_str(), nullptr, 10 ); +#else +#error "Need to define string to long long conversion for this compiler" +#endif + } + + ustring toUString( const XMLCh *const xml_str ) + { + ustring u_str; + if ( ( xml_str != nullptr ) && *xml_str ) + { + TranscodeToStr UTF8Transcoder( xml_str, "UTF-8" ); + u_str = ustring( reinterpret_cast( UTF8Transcoder.str() ) ); + } + return ( u_str ); + } + + ustring lookupAttribute( const Attributes &attributes, const XMLCh *attribute_name ) + { + XMLSize_t attr_index; + if ( !attributes.getIndex( attribute_name, attr_index ) ) + { + throw E57_EXCEPTION2( ErrorBadXMLFormat, "attributeName=" + toUString( attribute_name ) ); + } + return ( toUString( attributes.getValue( attr_index ) ) ); + } + + bool isAttributeDefined( const Attributes &attributes, const XMLCh *attribute_name ) + { + XMLSize_t attr_index; + return ( attributes.getIndex( attribute_name, attr_index ) ); + } +} + +//============================================================================= +// E57FileInputStream + +class E57FileInputStream : public BinInputStream +{ +public: + E57FileInputStream( CheckedFile *cf, uint64_t logicalStart, uint64_t logicalLength ); + ~E57FileInputStream() override = default; + + E57FileInputStream( const E57FileInputStream & ) = delete; + E57FileInputStream &operator=( const E57FileInputStream & ) = delete; + + XMLFilePos curPos() const override + { + return ( logicalPosition_ ); + } + + XMLSize_t readBytes( XMLByte *toFill, XMLSize_t maxToRead ) override; + + const XMLCh *getContentType() const override + { + return nullptr; + } + +private: + //??? lifetime of cf_ must be longer than this object! + CheckedFile *cf_; + uint64_t logicalStart_; + uint64_t logicalLength_; + uint64_t logicalPosition_; +}; + +E57FileInputStream::E57FileInputStream( CheckedFile *cf, uint64_t logicalStart, + uint64_t logicalLength ) : + cf_( cf ), + logicalStart_( logicalStart ), logicalLength_( logicalLength ), logicalPosition_( logicalStart ) +{ +} + +XMLSize_t E57FileInputStream::readBytes( XMLByte *const toFill, const XMLSize_t maxToRead ) +{ + if ( logicalPosition_ > logicalStart_ + logicalLength_ ) + { + return ( 0 ); + } + + int64_t available = logicalStart_ + logicalLength_ - logicalPosition_; + if ( available <= 0 ) + { + return ( 0 ); + } + + size_t maxToRead_size = maxToRead; + + // Be careful if size_t is smaller than int64_t + size_t available_size; + + // Assign to var to avoid MSVC warning + // This section can be simplified in C++17 using a "constexpr if". + constexpr bool cSizeCheck = ( sizeof( size_t ) >= sizeof( int64_t ) ); + if ( cSizeCheck ) + { + // size_t is at least as big as int64_t + available_size = static_cast( available ); + } + else + { + // size_t is smaller than int64_t, Calc max that size_t can hold + const int64_t size_max = std::numeric_limits::max(); + + // read smaller of size_max, available + //??? redo + if ( size_max < available ) + { + available_size = static_cast( size_max ); + } + else + { + available_size = static_cast( available ); + } + } + + size_t readCount = std::min( maxToRead_size, available_size ); + + cf_->seek( logicalPosition_ ); + cf_->read( reinterpret_cast( toFill ), readCount ); //??? cast ok? + logicalPosition_ += readCount; + return ( readCount ); +} + +//============================================================================= +// E57XmlFileInputSource + +E57XmlFileInputSource::E57XmlFileInputSource( CheckedFile *cf, uint64_t logicalStart, + uint64_t logicalLength ) : + InputSource( "E57File", + XMLPlatformUtils::fgMemoryManager ), //??? what if want to use our own memory + // manager?, what bufid is good? + cf_( cf ), logicalStart_( logicalStart ), logicalLength_( logicalLength ) +{ +} + +BinInputStream *E57XmlFileInputSource::makeStream() const +{ + return new E57FileInputStream( cf_, logicalStart_, logicalLength_ ); +} + +//============================================================================= +// E57XmlParser::ParseInfo + +E57XmlParser::ParseInfo::ParseInfo() : + nodeType( static_cast( 0 ) ), minimum( 0 ), maximum( 0 ), scale( 0 ), offset( 0 ), + precision( static_cast( 0 ) ), floatMinimum( 0 ), floatMaximum( 0 ), + fileOffset( 0 ), length( 0 ), allowHeterogeneousChildren( false ), recordCount( 0 ) +{ +} + +void E57XmlParser::ParseInfo::dump( int indent, std::ostream &os ) const +{ + os << space( indent ) << "nodeType: " << nodeType << std::endl; + os << space( indent ) << "minimum: " << minimum << std::endl; + os << space( indent ) << "maximum: " << maximum << std::endl; + os << space( indent ) << "scale: " << scale << std::endl; + os << space( indent ) << "offset: " << offset << std::endl; + os << space( indent ) << "precision: " << precision << std::endl; + os << space( indent ) << "floatMinimum: " << floatMinimum << std::endl; + os << space( indent ) << "floatMaximum: " << floatMaximum << std::endl; + os << space( indent ) << "fileOffset: " << fileOffset << std::endl; + os << space( indent ) << "length: " << length << std::endl; + os << space( indent ) << "allowHeterogeneousChildren: " << allowHeterogeneousChildren + << std::endl; + os << space( indent ) << "recordCount: " << recordCount << std::endl; + if ( container_ni ) + { + os << space( indent ) << "container_ni: " << std::endl; + } + else + { + os << space( indent ) << "container_ni: " << std::endl; + } + os << space( indent ) << "childText: \"" << childText << "\"" << std::endl; +} + +//============================================================================= +// E57XmlParser + +E57XmlParser::E57XmlParser( ImageFileImplSharedPtr imf ) : imf_( imf ), xmlReader( nullptr ) +{ +} + +E57XmlParser::~E57XmlParser() +{ + delete xmlReader; + + xmlReader = nullptr; + + XMLPlatformUtils::Terminate(); +} + +void E57XmlParser::init() +{ + // Initialize the XML4C2 system + try + { + XMLPlatformUtils::Initialize(); + } + catch ( const XMLException &ex ) + { + // Turn parser exception into E57Exception + throw E57_EXCEPTION2( ErrorXMLParserInit, + "parserMessage=" + ustring( XMLString::transcode( ex.getMessage() ) ) ); + } + + xmlReader = XMLReaderFactory::createXMLReader(); //??? auto_ptr? + + if ( xmlReader == nullptr ) + { + throw E57_EXCEPTION2( ErrorXMLParserInit, "could not create the xml reader" ); + } + + //??? check these are right + xmlReader->setFeature( XMLUni::fgSAX2CoreValidation, true ); + xmlReader->setFeature( XMLUni::fgXercesDynamic, true ); + xmlReader->setFeature( XMLUni::fgSAX2CoreNameSpaces, true ); + xmlReader->setFeature( XMLUni::fgXercesSchema, true ); + xmlReader->setFeature( XMLUni::fgXercesSchemaFullChecking, true ); + xmlReader->setFeature( XMLUni::fgSAX2CoreNameSpacePrefixes, true ); + + xmlReader->setContentHandler( this ); + xmlReader->setErrorHandler( this ); +} + +void E57XmlParser::parse( InputSource &inputSource ) +{ + xmlReader->parse( inputSource ); +} + +void E57XmlParser::startElement( const XMLCh *const uri, const XMLCh *const localName, + const XMLCh *const qName, const Attributes &attributes ) +{ +#ifdef E57_VERBOSE + std::cout << "startElement" << std::endl; + std::cout << space( 2 ) << "URI: " << toUString( uri ) << std::endl; + std::cout << space( 2 ) << "localName: " << toUString( localName ) << std::endl; + std::cout << space( 2 ) << "qName: " << toUString( qName ) << std::endl; + + for ( size_t i = 0; i < attributes.getLength(); i++ ) + { + std::cout << space( 2 ) << "Attribute[" << i << "]" << std::endl; + std::cout << space( 4 ) << "URI: " << toUString( attributes.getURI( i ) ) << std::endl; + std::cout << space( 4 ) << "localName: " << toUString( attributes.getLocalName( i ) ) + << std::endl; + std::cout << space( 4 ) << "qName: " << toUString( attributes.getQName( i ) ) + << std::endl; + std::cout << space( 4 ) << "value: " << toUString( attributes.getValue( i ) ) + << std::endl; + } +#endif + // Get Type attribute + ustring node_type = lookupAttribute( attributes, att_type ); + + //??? check to make sure not in primitive type (can only nest inside compound types). + + ParseInfo pi; + + if ( node_type == "Integer" ) + { +#ifdef E57_VERBOSE + std::cout << "got a Integer" << std::endl; +#endif + //??? check validity of numeric strings + pi.nodeType = TypeInteger; + + if ( isAttributeDefined( attributes, att_minimum ) ) + { + ustring minimum_str = lookupAttribute( attributes, att_minimum ); + + pi.minimum = convertStrToLL( minimum_str ); + } + else + { + // Not defined defined in XML, so defaults to E57_INT64_MIN + pi.minimum = INT64_MIN; + } + + if ( isAttributeDefined( attributes, att_maximum ) ) + { + ustring maximum_str = lookupAttribute( attributes, att_maximum ); + + pi.maximum = convertStrToLL( maximum_str ); + } + else + { + // Not defined defined in XML, so defaults to E57_INT64_MAX + pi.maximum = INT64_MAX; + } + + stack_.push( pi ); + } + else if ( node_type == "ScaledInteger" ) + { +#ifdef E57_VERBOSE + std::cout << "got a ScaledInteger" << std::endl; +#endif + pi.nodeType = TypeScaledInteger; + + //??? check validity of numeric strings + if ( isAttributeDefined( attributes, att_minimum ) ) + { + ustring minimum_str = lookupAttribute( attributes, att_minimum ); + + pi.minimum = convertStrToLL( minimum_str ); + } + else + { + // Not defined defined in XML, so defaults to E57_INT64_MIN + pi.minimum = INT64_MIN; + } + + if ( isAttributeDefined( attributes, att_maximum ) ) + { + ustring maximum_str = lookupAttribute( attributes, att_maximum ); + + pi.maximum = convertStrToLL( maximum_str ); + } + else + { + // Not defined defined in XML, so defaults to E57_INT64_MAX + pi.maximum = INT64_MAX; + } + + if ( isAttributeDefined( attributes, att_scale ) ) + { + ustring scale_str = lookupAttribute( attributes, att_scale ); + pi.scale = strToDouble( scale_str ); //??? use exact rounding library + } + else + { + // Not defined defined in XML, so defaults to 1.0 + pi.scale = 1.0; + } + + if ( isAttributeDefined( attributes, att_offset ) ) + { + ustring offset_str = lookupAttribute( attributes, att_offset ); + pi.offset = strToDouble( offset_str ); //??? use exact rounding library + } + else + { + // Not defined defined in XML, so defaults to 0.0 + pi.offset = 0.0; + } + + stack_.push( pi ); + } + else if ( node_type == "Float" ) + { +#ifdef E57_VERBOSE + std::cout << "got a Float" << std::endl; +#endif + pi.nodeType = TypeFloat; + + if ( isAttributeDefined( attributes, att_precision ) ) + { + ustring precision_str = lookupAttribute( attributes, att_precision ); + if ( precision_str == "single" ) + { + pi.precision = PrecisionSingle; + } + else if ( precision_str == "double" ) + { + pi.precision = PrecisionDouble; + } + else + { + throw E57_EXCEPTION2( ErrorBadXMLFormat, "precisionString=" + precision_str + + " fileName=" + imf_->fileName() + + " uri=" + toUString( uri ) + + " localName=" + toUString( localName ) + + " qName=" + toUString( qName ) ); + } + } + else + { + // Not defined defined in XML, so defaults to double + pi.precision = PrecisionDouble; + } + + if ( isAttributeDefined( attributes, att_minimum ) ) + { + ustring minimum_str = lookupAttribute( attributes, att_minimum ); + pi.floatMinimum = strToDouble( minimum_str ); //??? use exact rounding library + } + else + { + // Not defined defined in XML, so defaults to E57_FLOAT_MIN or E57_DOUBLE_MIN + if ( pi.precision == PrecisionSingle ) + { + pi.floatMinimum = FLOAT_MIN; + } + else + { + pi.floatMinimum = DOUBLE_MIN; + } + } + + if ( isAttributeDefined( attributes, att_maximum ) ) + { + ustring maximum_str = lookupAttribute( attributes, att_maximum ); + pi.floatMaximum = strToDouble( maximum_str ); //??? use exact rounding library + } + else + { + // Not defined defined in XML, so defaults to FLOAT_MAX or DOUBLE_MAX + if ( pi.precision == PrecisionSingle ) + { + pi.floatMaximum = FLOAT_MAX; + } + else + { + pi.floatMaximum = DOUBLE_MAX; + } + } + + stack_.push( pi ); + } + else if ( node_type == "String" ) + { +#ifdef E57_VERBOSE + std::cout << "got a String" << std::endl; +#endif + pi.nodeType = TypeString; + + stack_.push( pi ); + } + else if ( node_type == "Blob" ) + { +#ifdef E57_VERBOSE + std::cout << "got a Blob" << std::endl; +#endif + pi.nodeType = TypeBlob; + + //??? check validity of numeric strings + + // fileOffset is required to be defined + ustring fileOffset_str = lookupAttribute( attributes, att_fileOffset ); + + pi.fileOffset = convertStrToLL( fileOffset_str ); + + // length is required to be defined + ustring length_str = lookupAttribute( attributes, att_length ); + + pi.length = convertStrToLL( length_str ); + + stack_.push( pi ); + } + else if ( node_type == "Structure" ) + { +#ifdef E57_VERBOSE + std::cout << "got a Structure" << std::endl; +#endif + pi.nodeType = TypeStructure; + + // Read name space decls, if e57Root element + if ( toUString( localName ) == "e57Root" ) + { + // Search attributes for namespace declarations (only allowed in E57Root structure) + bool gotDefault = false; + for ( size_t i = 0; i < attributes.getLength(); i++ ) + { + // Check if declaring the default namespace + if ( toUString( attributes.getQName( i ) ) == "xmlns" ) + { +#ifdef E57_VERBOSE + std::cout << "declared default namespace, URI=" + << toUString( attributes.getValue( i ) ) << std::endl; +#endif + imf_->extensionsAdd( "", toUString( attributes.getValue( i ) ) ); + gotDefault = true; + } + + // Check if declaring a namespace + if ( toUString( attributes.getURI( i ) ) == "http://www.w3.org/2000/xmlns/" ) + { +#ifdef E57_VERBOSE + std::cout << "declared extension, prefix=" + << toUString( attributes.getLocalName( i ) ) + << " URI=" << toUString( attributes.getValue( i ) ) << std::endl; +#endif + imf_->extensionsAdd( toUString( attributes.getLocalName( i ) ), + toUString( attributes.getValue( i ) ) ); + } + } + + // If didn't declare a default namespace, have error + if ( !gotDefault ) + { + throw E57_EXCEPTION2( ErrorBadXMLFormat, "fileName=" + imf_->fileName() + + " uri=" + toUString( uri ) + + " localName=" + toUString( localName ) + + " qName=" + toUString( qName ) ); + } + } + + // Create container now, so can hold children + std::shared_ptr s_ni( new StructureNodeImpl( imf_ ) ); + pi.container_ni = s_ni; + + // After have Structure, check again if E57Root, if so mark attached so all children will be + // attached when added + if ( toUString( localName ) == "e57Root" ) + { + s_ni->setAttachedRecursive(); + } + + stack_.push( pi ); + } + else if ( node_type == "Vector" ) + { +#ifdef E57_VERBOSE + std::cout << "got a Vector" << std::endl; +#endif + pi.nodeType = TypeVector; + + if ( isAttributeDefined( attributes, att_allowHeterogeneousChildren ) ) + { + ustring allowHetero_str = lookupAttribute( attributes, att_allowHeterogeneousChildren ); + + int64_t i64 = convertStrToLL( allowHetero_str ); + + if ( i64 == 0 ) + { + pi.allowHeterogeneousChildren = false; + } + else if ( i64 == 1 ) + { + pi.allowHeterogeneousChildren = true; + } + else + { + throw E57_EXCEPTION2( ErrorBadXMLFormat, + "allowHeterogeneousChildren=" + toString( i64 ) + + "fileName=" + imf_->fileName() + " uri=" + toUString( uri ) + + " localName=" + toUString( localName ) + + " qName=" + toUString( qName ) ); + } + } + else + { + // Not defined defined in XML, so defaults to false + pi.allowHeterogeneousChildren = false; + } + + // Create container now, so can hold children + std::shared_ptr v_ni( + new VectorNodeImpl( imf_, pi.allowHeterogeneousChildren ) ); + pi.container_ni = v_ni; + + stack_.push( pi ); + } + else if ( node_type == "CompressedVector" ) + { +#ifdef E57_VERBOSE + std::cout << "got a CompressedVector" << std::endl; +#endif + pi.nodeType = TypeCompressedVector; + + // fileOffset is required to be defined + ustring fileOffset_str = lookupAttribute( attributes, att_fileOffset ); + + pi.fileOffset = convertStrToLL( fileOffset_str ); + + // recordCount is required to be defined + ustring recordCount_str = lookupAttribute( attributes, att_recordCount ); + + pi.recordCount = convertStrToLL( recordCount_str ); + + // Create container now, so can hold children + std::shared_ptr cv_ni( new CompressedVectorNodeImpl( imf_ ) ); + cv_ni->setRecordCount( pi.recordCount ); + cv_ni->setBinarySectionLogicalStart( + imf_->file_->physicalToLogical( pi.fileOffset ) ); //??? what if file_ is NULL? + pi.container_ni = cv_ni; + + stack_.push( pi ); + } + else + { + throw E57_EXCEPTION2( ErrorBadXMLFormat, + "nodeType=" + node_type + " fileName=" + imf_->fileName() + + " uri=" + toUString( uri ) + " localName=" + toUString( localName ) + + " qName=" + toUString( qName ) ); + } +#ifdef E57_VERBOSE + pi.dump( 4 ); +#endif +} + +void E57XmlParser::endElement( const XMLCh *const uri, const XMLCh *const localName, + const XMLCh *const qName ) +{ +#ifdef E57_VERBOSE + std::cout << "endElement" << std::endl; +#endif + + // Pop the node that just ended + ParseInfo pi = stack_.top(); //??? really want to make a copy here? + stack_.pop(); +#ifdef E57_VERBOSE + pi.dump( 4 ); +#endif + + // We should now have all the info we need to create the node + NodeImplSharedPtr current_ni; + + switch ( pi.nodeType ) + { + case TypeStructure: + case TypeVector: + current_ni = pi.container_ni; + break; + case TypeCompressedVector: + { + // Verify that both prototype and codecs child elements were defined + // ??? + current_ni = pi.container_ni; + } + break; + case TypeInteger: + { + // Convert child text (if any) to value, else default to 0.0 + int64_t intValue; + if ( pi.childText.length() > 0 ) + { + intValue = convertStrToLL( pi.childText ); + } + else + { + intValue = 0; + } + std::shared_ptr i_ni( + new IntegerNodeImpl( imf_, intValue, pi.minimum, pi.maximum ) ); + current_ni = i_ni; + } + break; + case TypeScaledInteger: + { + // Convert child text (if any) to value, else default to 0.0 + int64_t intValue; + if ( pi.childText.length() > 0 ) + { + intValue = convertStrToLL( pi.childText ); + } + else + { + intValue = 0; + } + std::shared_ptr si_ni( new ScaledIntegerNodeImpl( + imf_, intValue, pi.minimum, pi.maximum, pi.scale, pi.offset ) ); + current_ni = si_ni; + } + break; + case TypeFloat: + { + // Convert child text (if any) to value + double floatValue = 0.0; + bool validValue = false; + + if ( pi.childText.length() > 0 ) + { + floatValue = strToDouble( pi.childText ); + validValue = true; + } + + std::shared_ptr f_ni( new FloatNodeImpl( + imf_, floatValue, validValue, pi.precision, pi.floatMinimum, pi.floatMaximum ) ); + current_ni = f_ni; + } + break; + case TypeString: + { + std::shared_ptr s_ni( new StringNodeImpl( imf_, pi.childText ) ); + current_ni = s_ni; + } + break; + case TypeBlob: + { + std::shared_ptr b_ni( new BlobNodeImpl( imf_, pi.fileOffset, pi.length ) ); + current_ni = b_ni; + } + break; + default: + throw E57_EXCEPTION2( + ErrorInternal, "nodeType=" + toString( pi.nodeType ) + " fileName=" + imf_->fileName() + + " uri=" + toUString( uri ) + " localName=" + toUString( localName ) + + " qName=" + toUString( qName ) ); + } +#ifdef E57_VERBOSE + current_ni->dump( 4 ); +#endif + + // If first node in file ended, we are all done + if ( stack_.empty() ) + { + // Top level should be Structure + if ( current_ni->type() != TypeStructure ) + { + throw E57_EXCEPTION2( ErrorBadXMLFormat, "currentType=" + toString( current_ni->type() ) + + " fileName=" + imf_->fileName() + + " uri=" + toUString( uri ) + + " localName=" + toUString( localName ) + + " qName=" + toUString( qName ) ); + } + imf_->root_ = std::static_pointer_cast( current_ni ); + return; + } + + // Get next level up node (when entered function), which should be a container. + NodeImplSharedPtr parent_ni = stack_.top().container_ni; + + if ( !parent_ni ) + { + throw E57_EXCEPTION2( ErrorBadXMLFormat, "fileName=" + imf_->fileName() + + " uri=" + toUString( uri ) + + " localName=" + toUString( localName ) + + " qName=" + toUString( qName ) ); + } + + // Add current node into parent at top of stack + switch ( parent_ni->type() ) + { + case TypeStructure: + { + std::shared_ptr struct_ni = + std::static_pointer_cast( parent_ni ); + + // Add named child to structure + struct_ni->set( toUString( qName ), current_ni ); + } + break; + case TypeVector: + { + std::shared_ptr vector_ni = + std::static_pointer_cast( parent_ni ); + + // Add unnamed child to vector + vector_ni->append( current_ni ); + } + break; + case TypeCompressedVector: + { + std::shared_ptr cv_ni = + std::static_pointer_cast( parent_ni ); + ustring uQName = toUString( qName ); + + // n can be either prototype or codecs + if ( uQName == "prototype" ) + { + cv_ni->setPrototype( current_ni ); + } + else if ( uQName == "codecs" ) + { + if ( current_ni->type() != TypeVector ) + { + throw E57_EXCEPTION2( + ErrorBadXMLFormat, + "currentType=" + toString( current_ni->type() ) + + " fileName=" + imf_->fileName() + " uri=" + toUString( uri ) + + " localName=" + toUString( localName ) + " qName=" + toUString( qName ) ); + } + std::shared_ptr vi = + std::static_pointer_cast( current_ni ); + + // Check VectorNode is hetero + if ( !vi->allowHeteroChildren() ) + { + throw E57_EXCEPTION2( + ErrorBadXMLFormat, + "currentType=" + toString( current_ni->type() ) + + " fileName=" + imf_->fileName() + " uri=" + toUString( uri ) + + " localName=" + toUString( localName ) + " qName=" + toUString( qName ) ); + } + + cv_ni->setCodecs( vi ); + } + else + { + // Found unknown XML child element of CompressedVector, not prototype or codecs + throw E57_EXCEPTION2( ErrorBadXMLFormat, +"fileName=" + imf_->fileName() + + " uri=" + toUString( uri ) + + " localName=" + toUString( localName ) + + " qName=" + toUString( qName ) ); + } + } + break; + default: + // Have bad XML nesting, parent should have been a container. + throw E57_EXCEPTION2( ErrorBadXMLFormat, "parentType=" + toString( parent_ni->type() ) + + " fileName=" + imf_->fileName() + + " uri=" + toUString( uri ) + + " localName=" + toUString( localName ) + + " qName=" + toUString( qName ) ); + } +} + +void E57XmlParser::characters( const XMLCh *const chars, const XMLSize_t length ) +{ +//??? use length to make ustring +#ifdef E57_VERBOSE + std::cout << "characters, chars=\"" << toUString( chars ) << "\" length=" << length << std::endl; +#else + UNUSED( length ); +#endif + + // Get active element + ParseInfo &pi = stack_.top(); + + // Check if child text is allowed for current E57 element type + switch ( pi.nodeType ) + { + case TypeStructure: + case TypeVector: + case TypeCompressedVector: + case TypeBlob: + { + // If characters aren't whitespace, have an error, else ignore + ustring s = toUString( chars ); + if ( s.find_first_not_of( " \t\n\r" ) != std::string::npos ) + { + throw E57_EXCEPTION2( ErrorBadXMLFormat, "chars=" + toUString( chars ) ); + } + } + break; + default: + // Append to any previous characters + pi.childText += toUString( chars ); + } +} + +void E57XmlParser::error( const SAXParseException &ex ) +{ + throw E57_EXCEPTION2( + ErrorXMLParser, "systemId=" + ustring( XMLString::transcode( ex.getSystemId() ) ) + + " xmlLine=" + toString( ex.getLineNumber() ) + + " xmlColumn=" + toString( ex.getColumnNumber() ) + + " parserMessage=" + ustring( XMLString::transcode( ex.getMessage() ) ) ); +} + +void E57XmlParser::fatalError( const SAXParseException &ex ) +{ + throw E57_EXCEPTION2( + ErrorXMLParser, "systemId=" + ustring( XMLString::transcode( ex.getSystemId() ) ) + + " xmlLine=" + toString( ex.getLineNumber() ) + + " xmlColumn=" + toString( ex.getColumnNumber() ) + + " parserMessage=" + ustring( XMLString::transcode( ex.getMessage() ) ) ); +} + +void E57XmlParser::warning( const SAXParseException &ex ) +{ + // Don't take any action on warning from parser, just report + std::cerr << "**** XML parser warning: " << ustring( XMLString::transcode( ex.getMessage() ) ) + << std::endl; + std::cerr << " Debug info:" << std::endl; + std::cerr << " systemId=" << XMLString::transcode( ex.getSystemId() ) << std::endl; + std::cerr << ", xmlLine=" << ex.getLineNumber() << std::endl; + std::cerr << ", xmlColumn=" << ex.getColumnNumber() << std::endl; +} diff --git a/src/3rdParty/libE57Format/src/E57XmlParser.h b/src/3rdParty/libE57Format/src/E57XmlParser.h index 910aef8fc17af..e1a5f869216ba 100644 --- a/src/3rdParty/libE57Format/src/E57XmlParser.h +++ b/src/3rdParty/libE57Format/src/E57XmlParser.h @@ -1,126 +1,122 @@ -/* - * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) - * Modified work Copyright 2018 - 2020 Andy Maloney - * - * Permission is hereby granted, free of charge, to any person or organization - * obtaining a copy of the software and accompanying documentation covered by - * this license (the "Software") to use, reproduce, display, distribute, - * execute, and transmit the Software, and to prepare derivative works of the - * Software, and to permit third-parties to whom the Software is furnished to - * do so, all subject to the following: - * - * The copyright notices in the Software and this entire statement, including - * the above license grant, this restriction and the following disclaimer, - * must be included in all copies of the Software, in whole or in part, and - * all derivative works of the Software, unless such copies or derivative - * works are solely in the form of machine-executable object code generated by - * a source language processor. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT - * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE - * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - */ - -#pragma once - -#include -#include - -#include -#include - -#include "Common.h" - -using namespace XERCES_CPP_NAMESPACE; - -namespace XERCES_CPP_NAMESPACE -{ - class SAX2XMLReader; -} - -namespace e57 -{ - class CheckedFile; - - class E57XmlParser : public DefaultHandler - { - public: - E57XmlParser( ImageFileImplSharedPtr imf ); - ~E57XmlParser() override; - - void init(); - - void parse( InputSource &inputSource ); - - private: - /// SAX interface - void startElement( const XMLCh *const uri, const XMLCh *const localName, const XMLCh *const qName, - const Attributes &attributes ) override; - void endElement( const XMLCh *const uri, const XMLCh *const localName, const XMLCh *const qName ) override; - void characters( const XMLCh *const chars, const XMLSize_t length ) override; - - /// SAX error interface - void warning( const SAXParseException &ex ) override; - void error( const SAXParseException &ex ) override; - void fatalError( const SAXParseException &ex ) override; - - ustring toUString( const XMLCh *const xml_str ); - ustring lookupAttribute( const Attributes &attributes, const XMLCh *attribute_name ); - bool isAttributeDefined( const Attributes &attributes, const XMLCh *attribute_name ); - - ImageFileImplSharedPtr imf_; /// Image file we are reading - - struct ParseInfo - { - /// All the fields need to remember while parsing the XML - /// Not all fields are used at same time, depends on node type - /// Needed because not all info is available at one time to create the - /// node. - NodeType nodeType; // used by all types - int64_t minimum; // used in E57_INTEGER, E57_SCALED_INTEGER - int64_t maximum; // used in E57_INTEGER, E57_SCALED_INTEGER - double scale; // used in E57_SCALED_INTEGER - double offset; // used in E57_SCALED_INTEGER - FloatPrecision precision; // used in E57_FLOAT - double floatMinimum; // used in E57_FLOAT - double floatMaximum; // used in E57_FLOAT - int64_t fileOffset; // used in E57_BLOB, E57_COMPRESSED_VECTOR - int64_t length; // used in E57_BLOB - bool allowHeterogeneousChildren; // used in E57_VECTOR - int64_t recordCount; // used in E57_COMPRESSED_VECTOR - ustring childText; // used by all types, accumulates all child text between tags - - /// Holds node for Structure, Vector, and CompressedVector so can append - /// child elements - NodeImplSharedPtr container_ni; - - ParseInfo(); // default ctor - void dump( int indent = 0, std::ostream &os = std::cout ) const; - }; - std::stack stack_; /// Stores the current path in tree we are reading - - SAX2XMLReader *xmlReader; - }; - - class E57XmlFileInputSource : public InputSource - { - public: - E57XmlFileInputSource( CheckedFile *cf, uint64_t logicalStart, uint64_t logicalLength ); - ~E57XmlFileInputSource() override = default; - - E57XmlFileInputSource( const E57XmlFileInputSource & ) = delete; - E57XmlFileInputSource &operator=( const E57XmlFileInputSource & ) = delete; - - BinInputStream *makeStream() const override; - - private: - //??? lifetime of cf_ must be longer than this object! - CheckedFile *cf_; - uint64_t logicalStart_; - uint64_t logicalLength_; - }; -} +/* + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#pragma once + +#include + +#include +#include + +#include "Common.h" + +using namespace XERCES_CPP_NAMESPACE; + +namespace XERCES_CPP_NAMESPACE +{ + class SAX2XMLReader; +} + +namespace e57 +{ + class CheckedFile; + + class E57XmlParser : public DefaultHandler + { + public: + explicit E57XmlParser( ImageFileImplSharedPtr imf ); + ~E57XmlParser() override; + + void init(); + + void parse( InputSource &inputSource ); + + private: + /// SAX interface + void startElement( const XMLCh *uri, const XMLCh *localName, const XMLCh *qName, + const Attributes &attributes ) override; + void endElement( const XMLCh *uri, const XMLCh *localName, const XMLCh *qName ) override; + void characters( const XMLCh *chars, XMLSize_t length ) override; + + /// SAX error interface + void warning( const SAXParseException &ex ) override; + void error( const SAXParseException &ex ) override; + void fatalError( const SAXParseException &ex ) override; + + ImageFileImplSharedPtr imf_; /// Image file we are reading + + struct ParseInfo + { + // All the fields need to remember while parsing the XML + // Not all fields are used at same time, depends on node type + // Needed because not all info is available at one time to create the + // node. + NodeType nodeType; // used by all types + int64_t minimum; // used in Integer, ScaledInteger + int64_t maximum; // used in Integer, ScaledInteger + double scale; // used in ScaledInteger + double offset; // used in ScaledInteger + FloatPrecision precision; // used in Float + double floatMinimum; // used in Float + double floatMaximum; // used in Float + int64_t fileOffset; // used in Blob, CompressedVector + int64_t length; // used in Blob + bool allowHeterogeneousChildren; // used in Vector + int64_t recordCount; // used in CompressedVector + ustring childText; // used by all types, accumulates all child text between tags + + // Holds node for Structure, Vector, and CompressedVector so can append + // child elements + NodeImplSharedPtr container_ni; + + ParseInfo(); // default ctor + void dump( int indent = 0, std::ostream &os = std::cout ) const; + }; + + std::stack stack_; /// Stores the current path in tree we are reading + + SAX2XMLReader *xmlReader; + }; + + class E57XmlFileInputSource : public InputSource + { + public: + E57XmlFileInputSource( CheckedFile *cf, uint64_t logicalStart, uint64_t logicalLength ); + ~E57XmlFileInputSource() override = default; + + E57XmlFileInputSource( const E57XmlFileInputSource & ) = delete; + E57XmlFileInputSource &operator=( const E57XmlFileInputSource & ) = delete; + + BinInputStream *makeStream() const override; + + private: + //??? lifetime of cf_ must be longer than this object! + CheckedFile *cf_; + uint64_t logicalStart_; + uint64_t logicalLength_; + }; +} diff --git a/src/3rdParty/libE57Format/src/Encoder.cpp b/src/3rdParty/libE57Format/src/Encoder.cpp index a561643d36094..930bb72596a63 100644 --- a/src/3rdParty/libE57Format/src/Encoder.cpp +++ b/src/3rdParty/libE57Format/src/Encoder.cpp @@ -36,50 +36,54 @@ #include "Packet.h" #include "ScaledIntegerNodeImpl.h" #include "SourceDestBufferImpl.h" +#include "StringFunctions.h" using namespace e57; std::shared_ptr Encoder::EncoderFactory( unsigned bytestreamNumber, std::shared_ptr cVector, - std::vector &sbufs, ustring & /*codecPath*/ ) + std::vector &sbufs, + ustring & /*codecPath*/ ) { //??? For now, only handle one input if ( sbufs.size() != 1 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "sbufsSize=" + toString( sbufs.size() ) ); + throw E57_EXCEPTION2( ErrorInternal, "sbufsSize=" + toString( sbufs.size() ) ); } SourceDestBuffer sbuf = sbufs.at( 0 ); - /// Get node we are going to encode from the CompressedVector's prototype + // Get node we are going to encode from the CompressedVector's prototype NodeImplSharedPtr prototype = cVector->getPrototype(); ustring path = sbuf.pathName(); NodeImplSharedPtr encodeNode = prototype->get( path ); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "Node to encode:" << std::endl; //??? encodeNode->dump( 2 ); #endif switch ( encodeNode->type() ) { - case E57_INTEGER: + case TypeInteger: { std::shared_ptr ini = std::static_pointer_cast( encodeNode ); // downcast to correct type - /// Get pointer to parent ImageFileImpl, to call bitsNeeded() - ImageFileImplSharedPtr imf( encodeNode->destImageFile_ ); //??? should be function for this, - // imf->parentFile() - //--> ImageFile? + // Get pointer to parent ImageFileImpl, to call bitsNeeded() + ImageFileImplSharedPtr imf( + encodeNode->destImageFile_ ); //??? should be function for this, + // imf->parentFile() + //--> ImageFile? unsigned bitsPerRecord = imf->bitsNeeded( ini->minimum(), ini->maximum() ); - //!!! need to pick smarter channel buffer sizes, here and elsewhere - /// Construct Integer encoder with appropriate register size, based on - /// number of bits stored. + // !!! need to pick smarter channel buffer sizes, here and elsewhere + // Construct Integer encoder with appropriate register size, based on number of bits + // stored. if ( bitsPerRecord == 0 ) { - std::shared_ptr encoder( new ConstantIntegerEncoder( bytestreamNumber, sbuf, ini->minimum() ) ); + std::shared_ptr encoder( + new ConstantIntegerEncoder( bytestreamNumber, sbuf, ini->minimum() ) ); return encoder; } @@ -87,93 +91,100 @@ std::shared_ptr Encoder::EncoderFactory( unsigned bytestreamNumber, if ( bitsPerRecord <= 8 ) { std::shared_ptr encoder( new BitpackIntegerEncoder( - false, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, ini->minimum(), ini->maximum(), 1.0, 0.0 ) ); + false, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, ini->minimum(), + ini->maximum(), 1.0, 0.0 ) ); return encoder; } if ( bitsPerRecord <= 16 ) { std::shared_ptr encoder( new BitpackIntegerEncoder( - false, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, ini->minimum(), ini->maximum(), 1.0, 0.0 ) ); + false, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, ini->minimum(), + ini->maximum(), 1.0, 0.0 ) ); return encoder; } if ( bitsPerRecord <= 32 ) { std::shared_ptr encoder( new BitpackIntegerEncoder( - false, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, ini->minimum(), ini->maximum(), 1.0, 0.0 ) ); + false, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, ini->minimum(), + ini->maximum(), 1.0, 0.0 ) ); return encoder; } std::shared_ptr encoder( new BitpackIntegerEncoder( - false, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, ini->minimum(), ini->maximum(), 1.0, 0.0 ) ); + false, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, ini->minimum(), ini->maximum(), + 1.0, 0.0 ) ); return encoder; } - case E57_SCALED_INTEGER: + case TypeScaledInteger: { std::shared_ptr sini = - std::static_pointer_cast( encodeNode ); // downcast to correct type + std::static_pointer_cast( + encodeNode ); // downcast to correct type - /// Get pointer to parent ImageFileImpl, to call bitsNeeded() - ImageFileImplSharedPtr imf( encodeNode->destImageFile_ ); //??? should be function for this, - // imf->parentFile() - //--> ImageFile? + // Get pointer to parent ImageFileImpl, to call bitsNeeded() + ImageFileImplSharedPtr imf( + encodeNode->destImageFile_ ); //??? should be function for this, + // imf->parentFile() + //--> ImageFile? unsigned bitsPerRecord = imf->bitsNeeded( sini->minimum(), sini->maximum() ); - //!!! need to pick smarter channel buffer sizes, here and elsewhere - /// Construct ScaledInteger encoder with appropriate register size, - /// based on number of bits stored. + // !!! need to pick smarter channel buffer sizes, here and elsewhere + // Construct ScaledInteger encoder with appropriate register size, based on number of bits + // stored. if ( bitsPerRecord == 0 ) { - std::shared_ptr encoder( new ConstantIntegerEncoder( bytestreamNumber, sbuf, sini->minimum() ) ); + std::shared_ptr encoder( + new ConstantIntegerEncoder( bytestreamNumber, sbuf, sini->minimum() ) ); return encoder; } if ( bitsPerRecord <= 8 ) { - std::shared_ptr encoder( - new BitpackIntegerEncoder( true, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, - sini->minimum(), sini->maximum(), sini->scale(), sini->offset() ) ); + std::shared_ptr encoder( new BitpackIntegerEncoder( + true, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, sini->minimum(), + sini->maximum(), sini->scale(), sini->offset() ) ); return encoder; } if ( bitsPerRecord <= 16 ) { - std::shared_ptr encoder( - new BitpackIntegerEncoder( true, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, - sini->minimum(), sini->maximum(), sini->scale(), sini->offset() ) ); + std::shared_ptr encoder( new BitpackIntegerEncoder( + true, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, sini->minimum(), + sini->maximum(), sini->scale(), sini->offset() ) ); return encoder; } if ( bitsPerRecord <= 32 ) { - std::shared_ptr encoder( - new BitpackIntegerEncoder( true, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, - sini->minimum(), sini->maximum(), sini->scale(), sini->offset() ) ); + std::shared_ptr encoder( new BitpackIntegerEncoder( + true, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, sini->minimum(), + sini->maximum(), sini->scale(), sini->offset() ) ); return encoder; } - std::shared_ptr encoder( - new BitpackIntegerEncoder( true, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, sini->minimum(), - sini->maximum(), sini->scale(), sini->offset() ) ); + std::shared_ptr encoder( new BitpackIntegerEncoder( + true, bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, sini->minimum(), sini->maximum(), + sini->scale(), sini->offset() ) ); return encoder; } - case E57_FLOAT: + case TypeFloat: { std::shared_ptr fni = std::static_pointer_cast( encodeNode ); // downcast to correct type - //!!! need to pick smarter channel buffer sizes, here and elsewhere - std::shared_ptr encoder( - new BitpackFloatEncoder( bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, fni->precision() ) ); + // !!! need to pick smarter channel buffer sizes, here and elsewhere + std::shared_ptr encoder( new BitpackFloatEncoder( + bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/, fni->precision() ) ); return encoder; } - case E57_STRING: + case TypeString: { std::shared_ptr encoder( new BitpackStringEncoder( bytestreamNumber, sbuf, DATA_PACKET_MAX /*!!!*/ ) ); @@ -183,7 +194,7 @@ std::shared_ptr Encoder::EncoderFactory( unsigned bytestreamNumber, default: { - throw E57_EXCEPTION2( E57_ERROR_BAD_PROTOTYPE, "nodeType=" + toString( encodeNode->type() ) ); + throw E57_EXCEPTION2( ErrorBadPrototype, "nodeType=" + toString( encodeNode->type() ) ); } } } @@ -192,20 +203,20 @@ Encoder::Encoder( unsigned bytestreamNumber ) : bytestreamNumber_( bytestreamNum { } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void Encoder::dump( int indent, std::ostream &os ) const { os << space( indent ) << "bytestreamNumber: " << bytestreamNumber_ << std::endl; } #endif -///================ +//================ -BitpackEncoder::BitpackEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, unsigned outputMaxSize, - unsigned alignmentSize ) : +BitpackEncoder::BitpackEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, + unsigned outputMaxSize, unsigned alignmentSize ) : Encoder( bytestreamNumber ), - sourceBuffer_( sbuf.impl() ), outBuffer_( outputMaxSize ), outBufferFirst_( 0 ), outBufferEnd_( 0 ), - outBufferAlignmentSize_( alignmentSize ), currentRecordIndex_( 0 ) + sourceBuffer_( sbuf.impl() ), outBuffer_( outputMaxSize ), outBufferFirst_( 0 ), + outBufferEnd_( 0 ), outBufferAlignmentSize_( alignmentSize ), currentRecordIndex_( 0 ) { } @@ -226,27 +237,29 @@ size_t BitpackEncoder::outputAvailable() const void BitpackEncoder::outputRead( char *dest, const size_t byteCount ) { -#ifdef E57_MAX_VERBOSE - std::cout << "BitpackEncoder::outputRead() called, dest=" << dest << " byteCount=" << byteCount << std::endl; //??? +#ifdef E57_VERBOSE + std::cout << "BitpackEncoder::outputRead() called, dest=" << dest << " byteCount=" << byteCount + << std::endl; //??? #endif - /// Check we have enough bytes in queue + // Check we have enough bytes in queue if ( byteCount > outputAvailable() ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "byteCount=" + toString( byteCount ) + - " outputAvailable=" + toString( outputAvailable() ) ); + throw E57_EXCEPTION2( ErrorInternal, "byteCount=" + toString( byteCount ) + + " outputAvailable=" + toString( outputAvailable() ) ); } - /// Copy output bytes to caller + // Copy output bytes to caller memcpy( dest, &outBuffer_[outBufferFirst_], byteCount ); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE { unsigned i; for ( i = 0; i < byteCount && i < 20; i++ ) { - std::cout << " outBuffer[" << outBufferFirst_ + i - << "]=" << static_cast( static_cast( outBuffer_[outBufferFirst_ + i] ) ) + std::cout << " outBuffer[" << outBufferFirst_ + i << "]=" + << static_cast( + static_cast( outBuffer_[outBufferFirst_ + i] ) ) << std::endl; //??? } @@ -257,11 +270,11 @@ void BitpackEncoder::outputRead( char *dest, const size_t byteCount ) } #endif - /// Advance head pointer. + // Advance head pointer. outBufferFirst_ += byteCount; - /// Don't slide remaining data down now, wait until do some more processing - /// (that's when data needs to be aligned). + // Don't slide remaining data down now, wait until do some more processing (that's when data + // needs to be aligned). } void BitpackEncoder::outputClear() @@ -272,10 +285,10 @@ void BitpackEncoder::outputClear() void BitpackEncoder::sourceBufferSetNew( std::vector &sbufs ) { - /// Verify that this encoder only has single input buffer + // Verify that this encoder only has single input buffer if ( sbufs.size() != 1 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "sbufsSize=" + toString( sbufs.size() ) ); + throw E57_EXCEPTION2( ErrorInternal, "sbufsSize=" + toString( sbufs.size() ) ); } sourceBuffer_ = sbufs.at( 0 ).impl(); @@ -283,13 +296,13 @@ void BitpackEncoder::sourceBufferSetNew( std::vector &sbufs ) size_t BitpackEncoder::outputGetMaxSize() { - /// Its size that matters here, not capacity + // Its size that matters here, not capacity return ( outBuffer_.size() ); } void BitpackEncoder::outputSetMaxSize( unsigned byteCount ) { - /// Ignore if trying to shrink buffer (queue might get messed up). + // Ignore if trying to shrink buffer (queue might get messed up). if ( byteCount > outBuffer_.size() ) { outBuffer_.resize( byteCount ); @@ -298,20 +311,20 @@ void BitpackEncoder::outputSetMaxSize( unsigned byteCount ) void BitpackEncoder::outBufferShiftDown() { - /// Move data down closer to beginning of outBuffer_. - /// But keep outBufferEnd_ as a multiple of outBufferAlignmentSize_. - /// This ensures that writes into buffer can occur on natural boundaries. - /// Otherwise some CPUs will fault. + // Move data down closer to beginning of outBuffer_. + // But keep outBufferEnd_ as a multiple of outBufferAlignmentSize_. + // This ensures that writes into buffer can occur on natural boundaries. + // Otherwise some CPUs will fault. if ( outBufferFirst_ == outBufferEnd_ ) { - /// Buffer is empty, reset indices to 0 + // Buffer is empty, reset indices to 0 outBufferFirst_ = 0; outBufferEnd_ = 0; return; } - /// Round newEnd up to nearest multiple of outBufferAlignmentSize_. + // Round newEnd up to nearest multiple of outBufferAlignmentSize_. size_t newEnd = outputAvailable(); size_t remainder = newEnd % outBufferAlignmentSize_; if ( remainder > 0 ) @@ -321,31 +334,32 @@ void BitpackEncoder::outBufferShiftDown() size_t newFirst = outBufferFirst_ - ( outBufferEnd_ - newEnd ); size_t byteCount = outBufferEnd_ - outBufferFirst_; - /// Double check round up worked + // Double check round up worked if ( newEnd % outBufferAlignmentSize_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "newEnd=" + toString( newEnd ) + - " outBufferAlignmentSize=" + toString( outBufferAlignmentSize_ ) ); + throw E57_EXCEPTION2( ErrorInternal, + "newEnd=" + toString( newEnd ) + + " outBufferAlignmentSize=" + toString( outBufferAlignmentSize_ ) ); } - /// Be paranoid before memory copy + // Be paranoid before memory copy if ( newFirst + byteCount > outBuffer_.size() ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "newFirst=" + toString( newFirst ) + - " byteCount=" + toString( byteCount ) + - " outBufferSize=" + toString( outBuffer_.size() ) ); + throw E57_EXCEPTION2( ErrorInternal, "newFirst=" + toString( newFirst ) + + " byteCount=" + toString( byteCount ) + + " outBufferSize=" + toString( outBuffer_.size() ) ); } - /// Move available data down closer to beginning of outBuffer_. Overlapping - /// regions ok with memmove(). + // Move available data down closer to beginning of outBuffer_. Overlapping regions ok with + // memmove(). memmove( &outBuffer_[newFirst], &outBuffer_[outBufferFirst_], byteCount ); - /// Update indexes + // Update indexes outBufferFirst_ = newFirst; outBufferEnd_ = newEnd; } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void BitpackEncoder::dump( int indent, std::ostream &os ) const { Encoder::dump( indent, os ); @@ -361,7 +375,8 @@ void BitpackEncoder::dump( int indent, std::ostream &os ) const for ( i = 0; i < outBuffer_.size() && i < 20; i++ ) { os << space( indent + 4 ) << "outBuffer[" << i - << "]: " << static_cast( static_cast( outBuffer_.at( i ) ) ) << std::endl; + << "]: " << static_cast( static_cast( outBuffer_.at( i ) ) ) + << std::endl; } if ( i < outBuffer_.size() ) { @@ -372,78 +387,80 @@ void BitpackEncoder::dump( int indent, std::ostream &os ) const //================ -BitpackFloatEncoder::BitpackFloatEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, unsigned outputMaxSize, - FloatPrecision precision ) : +BitpackFloatEncoder::BitpackFloatEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, + unsigned outputMaxSize, FloatPrecision precision ) : BitpackEncoder( bytestreamNumber, sbuf, outputMaxSize, - ( precision == E57_SINGLE ) ? sizeof( float ) : sizeof( double ) ), + ( precision == PrecisionSingle ) ? sizeof( float ) : sizeof( double ) ), precision_( precision ) { } uint64_t BitpackFloatEncoder::processRecords( size_t recordCount ) { -#ifdef E57_MAX_VERBOSE - std::cout << " BitpackFloatEncoder::processRecords() called, recordCount=" << recordCount << std::endl; //??? +#ifdef E57_VERBOSE + std::cout << " BitpackFloatEncoder::processRecords() called, recordCount=" << recordCount + << std::endl; //??? #endif - /// Before we add any more, try to shift current contents of outBuffer_ down - /// to beginning of buffer. This leaves outBufferEnd_ at a natural boundary. + // Before we add any more, try to shift current contents of outBuffer_ down to beginning of + // buffer. This leaves outBufferEnd_ at a natural boundary. outBufferShiftDown(); - size_t typeSize = ( precision_ == E57_SINGLE ) ? sizeof( float ) : sizeof( double ); + size_t typeSize = ( precision_ == PrecisionSingle ) ? sizeof( float ) : sizeof( double ); -#ifdef E57_DEBUG - /// Verify that outBufferEnd_ is multiple of typeSize (so transfers of floats - /// are aligned naturally in memory). +#if VALIDATE_BASIC + // Verify that outBufferEnd_ is multiple of typeSize (so transfers of floats are aligned + // naturally in memory). if ( outBufferEnd_ % typeSize ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, - "outBufferEnd=" + toString( outBufferEnd_ ) + " typeSize=" + toString( typeSize ) ); + throw E57_EXCEPTION2( ErrorInternal, "outBufferEnd=" + toString( outBufferEnd_ ) + + " typeSize=" + toString( typeSize ) ); } #endif - /// Figure out how many records will fit in output. + // Figure out how many records will fit in output. size_t maxOutputRecords = ( outBuffer_.size() - outBufferEnd_ ) / typeSize; - /// Can't process more records than will safely fit in output stream + // Can't process more records than will safely fit in output stream if ( recordCount > maxOutputRecords ) { recordCount = maxOutputRecords; } - if ( precision_ == E57_SINGLE ) + if ( precision_ == PrecisionSingle ) { - /// Form the starting address for next available location in outBuffer + // Form the starting address for next available location in outBuffer auto outp = reinterpret_cast( &outBuffer_[outBufferEnd_] ); - /// Copy floats from sourceBuffer_ to outBuffer_ + // Copy floats from sourceBuffer_ to outBuffer_ for ( unsigned i = 0; i < recordCount; i++ ) { outp[i] = sourceBuffer_->getNextFloat(); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "encoding float: " << outp[i] << std::endl; #endif } } else - { /// E57_DOUBLE precision - /// Form the starting address for next available location in outBuffer + { + // Double precision + // Form the starting address for next available location in outBuffer auto outp = reinterpret_cast( &outBuffer_[outBufferEnd_] ); - /// Copy doubles from sourceBuffer_ to outBuffer_ + // Copy doubles from sourceBuffer_ to outBuffer_ for ( unsigned i = 0; i < recordCount; i++ ) { outp[i] = sourceBuffer_->getNextDouble(); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "encoding double: " << outp[i] << std::endl; #endif } } - /// Update end of outBuffer + // Update end of outBuffer outBufferEnd_ += recordCount * typeSize; - /// Update counts of records processed + // Update counts of records processed currentRecordIndex_ += recordCount; return ( currentRecordIndex_ ); @@ -451,26 +468,26 @@ uint64_t BitpackFloatEncoder::processRecords( size_t recordCount ) bool BitpackFloatEncoder::registerFlushToOutput() { - /// Since have no registers in encoder, return success + // Since have no registers in encoder, return success return ( true ); } float BitpackFloatEncoder::bitsPerRecord() { - return ( ( precision_ == E57_SINGLE ) ? 32.0F : 64.0F ); + return ( ( precision_ == PrecisionSingle ) ? 32.0F : 64.0F ); } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void BitpackFloatEncoder::dump( int indent, std::ostream &os ) const { BitpackEncoder::dump( indent, os ); - if ( precision_ == E57_SINGLE ) + if ( precision_ == PrecisionSingle ) { - os << space( indent ) << "precision: E57_SINGLE" << std::endl; + os << space( indent ) << "precision: Single" << std::endl; } else { - os << space( indent ) << "precision: E57_DOUBLE" << std::endl; + os << space( indent ) << "precision: Double" << std::endl; } } #endif @@ -480,38 +497,39 @@ void BitpackFloatEncoder::dump( int indent, std::ostream &os ) const BitpackStringEncoder::BitpackStringEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, unsigned outputMaxSize ) : BitpackEncoder( bytestreamNumber, sbuf, outputMaxSize, 1 ), - totalBytesProcessed_( 0 ), isStringActive_( false ), prefixComplete_( false ), currentCharPosition_( 0 ) + totalBytesProcessed_( 0 ), isStringActive_( false ), prefixComplete_( false ), + currentCharPosition_( 0 ) { } uint64_t BitpackStringEncoder::processRecords( size_t recordCount ) { -#ifdef E57_MAX_VERBOSE - std::cout << " BitpackStringEncoder::processRecords() called, recordCount=" << recordCount << std::endl; //??? +#ifdef E57_VERBOSE + std::cout << " BitpackStringEncoder::processRecords() called, recordCount=" << recordCount + << std::endl; //??? #endif - /// Before we add any more, try to shift current contents of outBuffer_ down - /// to beginning of buffer. + // Before we add any more, try to shift current contents of outBuffer_ down to beginning of + // buffer. outBufferShiftDown(); - /// Figure out how many bytes outBuffer can accept. + // Figure out how many bytes outBuffer can accept. size_t bytesFree = outBuffer_.size() - outBufferEnd_; - /// Form the starting address for next available location in outBuffer + // Form the starting address for next available location in outBuffer char *outp = &outBuffer_[outBufferEnd_]; unsigned recordsProcessed = 0; - /// Don't start loop unless have at least 8 bytes for worst case string - /// length prefix + // Don't start loop unless have at least 8 bytes for worst case string length prefix while ( recordsProcessed < recordCount && bytesFree >= 8 ) { //??? should be able to proceed if only 1 byte free if ( isStringActive_ && !prefixComplete_ ) { - /// Calc the length prefix, either 1 byte or 8 bytes + // Calc the length prefix, either 1 byte or 8 bytes size_t len = currentString_.length(); if ( len <= 127 ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "encoding short string: (len=" << len << ") " "" @@ -520,21 +538,21 @@ uint64_t BitpackStringEncoder::processRecords( size_t recordCount ) "" << std::endl; #endif - /// We can use the short length prefix: b0=0, b7-b1=len + // We can use the short length prefix: b0=0, b7-b1=len auto lengthPrefix = static_cast( len << 1 ); *outp++ = lengthPrefix; bytesFree--; } else { -#ifdef E57_DEBUG - /// Double check have space +#if VALIDATE_BASIC + // Double check have space if ( bytesFree < 8 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "bytesFree=" + toString( bytesFree ) ); + throw E57_EXCEPTION2( ErrorInternal, "bytesFree=" + toString( bytesFree ) ); } #endif -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "encoding long string: (len=" << len << ") " "" @@ -543,9 +561,8 @@ uint64_t BitpackStringEncoder::processRecords( size_t recordCount ) "" << std::endl; #endif - /// We use the long length prefix: b0=1, b63-b1=len, and store in - /// little endian order Shift the length and set the least - /// significant bit, b0=1. + // We use the long length prefix: b0=1, b63-b1=len, and store in little endian order + // Shift the length and set the least significant bit, b0=1. uint64_t lengthPrefix = ( static_cast( len ) << 1 ) | 1LL; *outp++ = static_cast( lengthPrefix ); *outp++ = static_cast( lengthPrefix >> ( 1 * 8 ) ); @@ -562,8 +579,9 @@ uint64_t BitpackStringEncoder::processRecords( size_t recordCount ) } if ( isStringActive_ ) { - /// Copy as much string as will fit in outBuffer - size_t bytesToProcess = std::min( currentString_.length() - currentCharPosition_, bytesFree ); + // Copy as much string as will fit in outBuffer + size_t bytesToProcess = + std::min( currentString_.length() - currentCharPosition_, bytesFree ); for ( size_t i = 0; i < bytesToProcess; i++ ) { @@ -574,7 +592,7 @@ uint64_t BitpackStringEncoder::processRecords( size_t recordCount ) totalBytesProcessed_ += bytesToProcess; bytesFree -= bytesToProcess; - /// Check if finished string + // Check if finished string if ( currentCharPosition_ == currentString_.length() ) { isStringActive_ = false; @@ -583,21 +601,21 @@ uint64_t BitpackStringEncoder::processRecords( size_t recordCount ) } if ( !isStringActive_ && recordsProcessed < recordCount ) { - /// Get next string from sourceBuffer + // Get next string from sourceBuffer currentString_ = sourceBuffer_->getNextString(); isStringActive_ = true; prefixComplete_ = false; currentCharPosition_ = 0; -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "getting next string, length=" << currentString_.length() << std::endl; #endif } } - /// Update end of outBuffer + // Update end of outBuffer outBufferEnd_ = outBuffer_.size() - bytesFree; - /// Update counts of records processed + // Update counts of records processed currentRecordIndex_ += recordsProcessed; return ( currentRecordIndex_ ); @@ -605,23 +623,23 @@ uint64_t BitpackStringEncoder::processRecords( size_t recordCount ) bool BitpackStringEncoder::registerFlushToOutput() { - /// Since have no registers in encoder, return success + // Since have no registers in encoder, return success return ( true ); } float BitpackStringEncoder::bitsPerRecord() { - /// Return average number of bits in strings + 8 bits for prefix + // Return average number of bits in strings + 8 bits for prefix if ( currentRecordIndex_ > 0 ) { return ( 8.0f * totalBytesProcessed_ ) / currentRecordIndex_ + 8; } - /// We haven't completed a record yet, so guess 100 bytes per record + // We haven't completed a record yet, so guess 100 bytes per record return 100 * 8.0f; } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void BitpackStringEncoder::dump( int indent, std::ostream &os ) const { BitpackEncoder::dump( indent, os ); @@ -636,13 +654,11 @@ void BitpackStringEncoder::dump( int indent, std::ostream &os ) const //================================================================ template -BitpackIntegerEncoder::BitpackIntegerEncoder( bool isScaledInteger, unsigned bytestreamNumber, - SourceDestBuffer &sbuf, unsigned outputMaxSize, - int64_t minimum, int64_t maximum, double scale, - double offset ) : +BitpackIntegerEncoder::BitpackIntegerEncoder( + bool isScaledInteger, unsigned bytestreamNumber, SourceDestBuffer &sbuf, unsigned outputMaxSize, + int64_t minimum, int64_t maximum, double scale, double offset ) : BitpackEncoder( bytestreamNumber, sbuf, outputMaxSize, sizeof( RegisterT ) ) { - /// Get pointer to parent ImageFileImpl ImageFileImplSharedPtr imf( sbuf.impl()->destImageFile() ); //??? should be function for this, // imf->parentFile() --> ImageFile? @@ -657,61 +673,63 @@ BitpackIntegerEncoder::BitpackIntegerEncoder( bool isScaledInteger, u register_ = 0; } -template uint64_t BitpackIntegerEncoder::processRecords( size_t recordCount ) +template +uint64_t BitpackIntegerEncoder::processRecords( size_t recordCount ) { //??? what are state guarantees if get an exception during transfer? -#ifdef E57_MAX_VERBOSE - std::cout << "BitpackIntegerEncoder::processRecords() called, sizeof(RegisterT)=" << sizeof( RegisterT ) - << " recordCount=" << recordCount << std::endl; +#ifdef E57_VERBOSE + std::cout << "BitpackIntegerEncoder::processRecords() called, sizeof(RegisterT)=" + << sizeof( RegisterT ) << " recordCount=" << recordCount << std::endl; dump( 4 ); #endif -#ifdef E57_MAX_DEBUG - /// Double check that register will hold at least one input records worth of - /// bits + +#if ( E57_VALIDATION_LEVEL == VALIDATION_DEEP ) + // Double check that register will hold at least one input records worth of bits if ( 8 * sizeof( RegisterT ) < bitsPerRecord_ ) - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "bitsPerRecord=" + toString( bitsPerRecord_ ) ); + { + throw E57_EXCEPTION2( ErrorInternal, "bitsPerRecord=" + toString( bitsPerRecord_ ) ); + } #endif - /// Before we add any more, try to shift current contents of outBuffer_ down - /// to beginning of buffer. This leaves outBufferEnd_ at a natural boundary. + // Before we add any more, try to shift current contents of outBuffer_ down to beginning of + // buffer. This leaves outBufferEnd_ at a natural boundary. outBufferShiftDown(); -#ifdef E57_DEBUG - /// Verify that outBufferEnd_ is multiple of sizeof(RegisterT) (so transfers - /// of RegisterT are aligned naturally in memory). +#ifdef VALIDATE_BASIC + // Verify that outBufferEnd_ is multiple of sizeof(RegisterT) (so transfers of RegisterT are + // aligned naturally in memory). if ( outBufferEnd_ % sizeof( RegisterT ) ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "outBufferEnd=" + toString( outBufferEnd_ ) ); + throw E57_EXCEPTION2( ErrorInternal, "outBufferEnd=" + toString( outBufferEnd_ ) ); } size_t transferMax = ( outBuffer_.size() - outBufferEnd_ ) / sizeof( RegisterT ); #endif - /// Precalculate exact maximum number of records that will fit in output - /// before overflow. + // Precalculate exact maximum number of records that will fit in output + // before overflow. size_t outputWordCapacity = ( outBuffer_.size() - outBufferEnd_ ) / sizeof( RegisterT ); - size_t maxOutputRecords = - ( outputWordCapacity * 8 * sizeof( RegisterT ) + 8 * sizeof( RegisterT ) - registerBitsUsed_ - 1 ) / - bitsPerRecord_; + size_t maxOutputRecords = ( outputWordCapacity * 8 * sizeof( RegisterT ) + + 8 * sizeof( RegisterT ) - registerBitsUsed_ - 1 ) / + bitsPerRecord_; - /// Number of transfers is the smaller of what was requested and what will - /// fit. + // Number of transfers is the smaller of what was requested and what will fit. recordCount = std::min( recordCount, maxOutputRecords ); -#ifdef E57_MAX_VERBOSE - std::cout << " outputWordCapacity=" << outputWordCapacity << " maxOutputRecords=" << maxOutputRecords - << " recordCount=" << recordCount << std::endl; +#ifdef E57_VERBOSE + std::cout << " outputWordCapacity=" << outputWordCapacity + << " maxOutputRecords=" << maxOutputRecords << " recordCount=" << recordCount + << std::endl; #endif - /// Form the starting address for next available location in outBuffer + // Form the starting address for next available location in outBuffer auto outp = reinterpret_cast( &outBuffer_[outBufferEnd_] ); unsigned outTransferred = 0; - /// Copy bits from sourceBuffer_ to outBuffer_ + // Copy bits from sourceBuffer_ to outBuffer_ for ( unsigned i = 0; i < recordCount; i++ ) { int64_t rawValue; - /// The parameter isScaledInteger_ determines which version of - /// getNextInt64 gets called + // The parameter isScaledInteger_ determines which version of getNextInt64 gets called if ( isScaledInteger_ ) { rawValue = sourceBuffer_->getNextInt64( scale_, offset_ ); @@ -721,67 +739,68 @@ template uint64_t BitpackIntegerEncoder::process rawValue = sourceBuffer_->getNextInt64(); } - /// Enforce min/max specification on value + // Enforce min/max specification on value if ( rawValue < minimum_ || maximum_ < rawValue ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_OUT_OF_BOUNDS, "rawValue=" + toString( rawValue ) + - " minimum=" + toString( minimum_ ) + - " maximum=" + toString( maximum_ ) ); + throw E57_EXCEPTION2( ErrorValueOutOfBounds, "rawValue=" + toString( rawValue ) + + " minimum=" + toString( minimum_ ) + + " maximum=" + toString( maximum_ ) ); } auto uValue = static_cast( rawValue - minimum_ ); -#ifdef E57_MAX_VERBOSE - std::cout << "encoding integer rawValue=" << binaryString( rawValue ) << " = " << hexString( rawValue ) - << std::endl; - std::cout << " uValue =" << binaryString( uValue ) << " = " << hexString( uValue ) << std::endl; +#ifdef E57_VERBOSE + std::cout << "encoding integer rawValue=" << binaryString( rawValue ) << " = " + << hexString( rawValue ) << std::endl; + std::cout << " uValue =" << binaryString( uValue ) << " = " + << hexString( uValue ) << std::endl; #endif -#ifdef E57_DEBUG - /// Double check that no bits outside of the mask are set +#ifdef VALIDATE_BASIC + // Double check that no bits outside of the mask are set if ( uValue & ~static_cast( sourceBitMask_ ) ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "uValue=" + toString( uValue ) ); + throw E57_EXCEPTION2( ErrorInternal, "uValue=" + toString( uValue ) ); } #endif - /// Mask off upper bits (just in case) + // Mask off upper bits (just in case) uValue &= static_cast( sourceBitMask_ ); - /// See if uValue bits will fit in register + // See if uValue bits will fit in register unsigned newRegisterBitsUsed = registerBitsUsed_ + bitsPerRecord_; -#ifdef E57_MAX_VERBOSE - std::cout << " registerBitsUsed=" << registerBitsUsed_ << " newRegisterBitsUsed=" << newRegisterBitsUsed - << std::endl; +#ifdef E57_VERBOSE + std::cout << " registerBitsUsed=" << registerBitsUsed_ + << " newRegisterBitsUsed=" << newRegisterBitsUsed << std::endl; #endif if ( newRegisterBitsUsed > 8 * sizeof( RegisterT ) ) { - /// Have more than one registers worth, fill register, transfer, then - /// fill some more + // Have more than one registers worth, fill register, transfer, then fill some more register_ |= static_cast( uValue ) << registerBitsUsed_; -#ifdef E57_DEBUG - /// Before transfer, double check address within bounds +#ifdef VALIDATE_BASIC + // Before transfer, double check address within bounds if ( outTransferred >= transferMax ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "outTransferred=" + toString( outTransferred ) + " transferMax" + - toString( transferMax ) ); + throw E57_EXCEPTION2( ErrorInternal, "outTransferred=" + toString( outTransferred ) + + " transferMax" + toString( transferMax ) ); } #endif outp[outTransferred] = register_; outTransferred++; - register_ = static_cast( uValue ) >> ( 8 * sizeof( RegisterT ) - registerBitsUsed_ ); + register_ = + static_cast( uValue ) >> ( 8 * sizeof( RegisterT ) - registerBitsUsed_ ); registerBitsUsed_ = newRegisterBitsUsed - 8 * sizeof( RegisterT ); } else if ( newRegisterBitsUsed == 8 * sizeof( RegisterT ) ) { - /// Input will exactly fill register, insert value, then transfer + // Input will exactly fill register, insert value, then transfer register_ |= static_cast( uValue ) << registerBitsUsed_; -#ifdef E57_DEBUG - /// Before transfer, double check address within bounds +#ifdef VALIDATE_BASIC + // Before transfer, double check address within bounds if ( outTransferred >= transferMax ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "outTransferred=" + toString( outTransferred ) + " transferMax" + - toString( transferMax ) ); + throw E57_EXCEPTION2( ErrorInternal, "outTransferred=" + toString( outTransferred ) + + " transferMax" + toString( transferMax ) ); } #endif outp[outTransferred] = register_; @@ -793,29 +812,29 @@ template uint64_t BitpackIntegerEncoder::process } else { - /// There is extra room in register, insert value, but don't do - /// transfer yet + // There is extra room in register, insert value, but don't do transfer yet register_ |= static_cast( uValue ) << registerBitsUsed_; registerBitsUsed_ = newRegisterBitsUsed; } -#ifdef E57_MAX_VERBOSE - std::cout << " After " << outTransferred << " transfers and " << i + 1 << " records, encoder:" << std::endl; +#ifdef E57_VERBOSE + std::cout << " After " << outTransferred << " transfers and " << i + 1 + << " records, encoder:" << std::endl; dump( 4 ); #endif } - /// Update tail of output buffer + // Update tail of output buffer outBufferEnd_ += outTransferred * sizeof( RegisterT ); -#ifdef E57_DEBUG - /// Double check end is ok +#ifdef VALIDATE_BASIC + // Double check end is ok if ( outBufferEnd_ > outBuffer_.size() ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "outBufferEnd=" + toString( outBufferEnd_ ) + - " outBuffersize=" + toString( outBuffer_.size() ) ); + throw E57_EXCEPTION2( ErrorInternal, "outBufferEnd=" + toString( outBufferEnd_ ) + + " outBuffersize=" + toString( outBuffer_.size() ) ); } #endif - /// Update counts of records processed + // Update counts of records processed currentRecordIndex_ += recordCount; return ( currentRecordIndex_ ); @@ -823,14 +842,14 @@ template uint64_t BitpackIntegerEncoder::process template bool BitpackIntegerEncoder::registerFlushToOutput() { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "BitpackIntegerEncoder::registerFlushToOutput() called, " "sizeof(RegisterT)=" << sizeof( RegisterT ) << std::endl; dump( 4 ); #endif - /// If have any used bits in register, transfer to output, padded in MSBits - /// with zeros to RegisterT boundary + // If have any used bits in register, transfer to output, padded in MSBits with zeros to + // RegisterT boundary if ( registerBitsUsed_ > 0 ) { if ( outBufferEnd_ < outBuffer_.size() - sizeof( RegisterT ) ) @@ -854,8 +873,9 @@ template float BitpackIntegerEncoder::bitsPerRec return ( static_cast( bitsPerRecord_ ) ); } -#ifdef E57_DEBUG -template void BitpackIntegerEncoder::dump( int indent, std::ostream &os ) const +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +template +void BitpackIntegerEncoder::dump( int indent, std::ostream &os ) const { BitpackEncoder::dump( indent, os ); os << space( indent ) << "isScaledInteger: " << isScaledInteger_ << std::endl; @@ -864,40 +884,43 @@ template void BitpackIntegerEncoder::dump( int i os << space( indent ) << "scale: " << scale_ << std::endl; os << space( indent ) << "offset: " << offset_ << std::endl; os << space( indent ) << "bitsPerRecord: " << bitsPerRecord_ << std::endl; - os << space( indent ) << "sourceBitMask: " << binaryString( sourceBitMask_ ) << " " << hexString( sourceBitMask_ ) - << std::endl; - os << space( indent ) << "register: " << binaryString( register_ ) << " " << hexString( register_ ) - << std::endl; + os << space( indent ) << "sourceBitMask: " << binaryString( sourceBitMask_ ) << " " + << hexString( sourceBitMask_ ) << std::endl; + os << space( indent ) << "register: " << binaryString( register_ ) << " " + << hexString( register_ ) << std::endl; os << space( indent ) << "registerBitsUsed: " << registerBitsUsed_ << std::endl; } #endif //================================================================ -ConstantIntegerEncoder::ConstantIntegerEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, int64_t minimum ) : - Encoder( bytestreamNumber ), sourceBuffer_( sbuf.impl() ), currentRecordIndex_( 0 ), minimum_( minimum ) +ConstantIntegerEncoder::ConstantIntegerEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, + int64_t minimum ) : + Encoder( bytestreamNumber ), + sourceBuffer_( sbuf.impl() ), currentRecordIndex_( 0 ), minimum_( minimum ) { } uint64_t ConstantIntegerEncoder::processRecords( size_t recordCount ) { -#ifdef E57_MAX_VERBOSE - std::cout << "ConstantIntegerEncoder::processRecords() called, recordCount=" << recordCount << std::endl; +#ifdef E57_VERBOSE + std::cout << "ConstantIntegerEncoder::processRecords() called, recordCount=" << recordCount + << std::endl; dump( 4 ); #endif - /// Check that all source values are == minimum_ + // Check that all source values are == minimum_ for ( unsigned i = 0; i < recordCount; i++ ) { int64_t nextInt64 = sourceBuffer_->getNextInt64(); if ( nextInt64 != minimum_ ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_OUT_OF_BOUNDS, - "nextInt64=" + toString( nextInt64 ) + " minimum=" + toString( minimum_ ) ); + throw E57_EXCEPTION2( ErrorValueOutOfBounds, "nextInt64=" + toString( nextInt64 ) + + " minimum=" + toString( minimum_ ) ); } } - /// Update counts of records processed + // Update counts of records processed currentRecordIndex_ += recordCount; return ( currentRecordIndex_ ); @@ -915,7 +938,7 @@ uint64_t ConstantIntegerEncoder::currentRecordIndex() float ConstantIntegerEncoder::bitsPerRecord() { - /// We don't produce any output + // We don't produce any output return ( 0.0 ); } @@ -926,16 +949,16 @@ bool ConstantIntegerEncoder::registerFlushToOutput() size_t ConstantIntegerEncoder::outputAvailable() const { - /// We don't produce any output + // We don't produce any output return 0; } void ConstantIntegerEncoder::outputRead( char * /*dest*/, const size_t byteCount ) { - /// Should never request any output data + // Should never request any output data if ( byteCount > 0 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "byteCount=" + toString( byteCount ) ); + throw E57_EXCEPTION2( ErrorInternal, "byteCount=" + toString( byteCount ) ); } } @@ -945,10 +968,10 @@ void ConstantIntegerEncoder::outputClear() void ConstantIntegerEncoder::sourceBufferSetNew( std::vector &sbufs ) { - /// Verify that this encoder only has single input buffer + // Verify that this encoder only has single input buffer if ( sbufs.size() != 1 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "sbufsSize=" + toString( sbufs.size() ) ); + throw E57_EXCEPTION2( ErrorInternal, "sbufsSize=" + toString( sbufs.size() ) ); } sourceBuffer_ = sbufs.at( 0 ).impl(); @@ -956,16 +979,16 @@ void ConstantIntegerEncoder::sourceBufferSetNew( std::vector & size_t ConstantIntegerEncoder::outputGetMaxSize() { - /// We don't produce any output + // We don't produce any output return ( 0 ); } void ConstantIntegerEncoder::outputSetMaxSize( unsigned /*byteCount*/ ) { - /// Ignore, since don't produce any output + // Ignore, since don't produce any output } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void ConstantIntegerEncoder::dump( int indent, std::ostream &os ) const { Encoder::dump( indent, os ); diff --git a/src/3rdParty/libE57Format/src/Encoder.h b/src/3rdParty/libE57Format/src/Encoder.h index 5bcea0c01eaa0..5806f6abbaea2 100644 --- a/src/3rdParty/libE57Format/src/Encoder.h +++ b/src/3rdParty/libE57Format/src/Encoder.h @@ -34,9 +34,9 @@ namespace e57 class Encoder { public: - static std::shared_ptr EncoderFactory( unsigned bytestreamNumber, - std::shared_ptr cVector, - std::vector &sbuf, ustring &codecPath ); + static std::shared_ptr EncoderFactory( + unsigned bytestreamNumber, std::shared_ptr cVector, + std::vector &sbuf, ustring &codecPath ); virtual ~Encoder() = default; @@ -46,8 +46,8 @@ namespace e57 virtual float bitsPerRecord() = 0; virtual bool registerFlushToOutput() = 0; - virtual size_t outputAvailable() const = 0; /// number of bytes that can be read - virtual void outputRead( char *dest, const size_t byteCount ) = 0; /// get data from encoder + virtual size_t outputAvailable() const = 0; /// number of bytes that can be read + virtual void outputRead( char *dest, size_t byteCount ) = 0; /// get data from encoder virtual void outputClear() = 0; virtual void sourceBufferSetNew( std::vector &sbufs ) = 0; @@ -59,11 +59,12 @@ namespace e57 return bytestreamNumber_; } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT virtual void dump( int indent = 0, std::ostream &os = std::cout ) const; #endif + protected: - Encoder( unsigned bytestreamNumber ); + explicit Encoder( unsigned bytestreamNumber ); unsigned bytestreamNumber_; }; @@ -77,18 +78,18 @@ namespace e57 float bitsPerRecord() override = 0; bool registerFlushToOutput() override = 0; - size_t outputAvailable() const override; /// number of bytes that can be read - void outputRead( char *dest, - const size_t byteCount ) override; /// get data from encoder + size_t outputAvailable() const override; /// number of bytes that can be read + void outputRead( char *dest, size_t byteCount ) override; /// get data from encoder void outputClear() override; void sourceBufferSetNew( std::vector &sbufs ) override; size_t outputGetMaxSize() override; void outputSetMaxSize( unsigned byteCount ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif + protected: BitpackEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, unsigned outputMaxSize, unsigned alignmentSize ); @@ -108,16 +109,17 @@ namespace e57 class BitpackFloatEncoder : public BitpackEncoder { public: - BitpackFloatEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, unsigned outputMaxSize, - FloatPrecision precision ); + BitpackFloatEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, + unsigned outputMaxSize, FloatPrecision precision ); uint64_t processRecords( size_t recordCount ) override; bool registerFlushToOutput() override; float bitsPerRecord() override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif + protected: FloatPrecision precision_; }; @@ -125,15 +127,17 @@ namespace e57 class BitpackStringEncoder : public BitpackEncoder { public: - BitpackStringEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, unsigned outputMaxSize ); + BitpackStringEncoder( unsigned bytestreamNumber, SourceDestBuffer &sbuf, + unsigned outputMaxSize ); uint64_t processRecords( size_t recordCount ) override; bool registerFlushToOutput() override; float bitsPerRecord() override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif + protected: uint64_t totalBytesProcessed_; bool isStringActive_; @@ -145,16 +149,18 @@ namespace e57 template class BitpackIntegerEncoder : public BitpackEncoder { public: - BitpackIntegerEncoder( bool isScaledInteger, unsigned bytestreamNumber, SourceDestBuffer &sbuf, - unsigned outputMaxSize, int64_t minimum, int64_t maximum, double scale, double offset ); + BitpackIntegerEncoder( bool isScaledInteger, unsigned bytestreamNumber, + SourceDestBuffer &sbuf, unsigned outputMaxSize, int64_t minimum, + int64_t maximum, double scale, double offset ); uint64_t processRecords( size_t recordCount ) override; bool registerFlushToOutput() override; float bitsPerRecord() override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif + protected: bool isScaledInteger_; int64_t minimum_; @@ -177,18 +183,18 @@ namespace e57 float bitsPerRecord() override; bool registerFlushToOutput() override; - size_t outputAvailable() const override; /// number of bytes that can be read - void outputRead( char *dest, - const size_t byteCount ) override; /// get data from encoder + size_t outputAvailable() const override; /// number of bytes that can be read + void outputRead( char *dest, size_t byteCount ) override; /// get data from encoder void outputClear() override; void sourceBufferSetNew( std::vector &sbufs ) override; size_t outputGetMaxSize() override; void outputSetMaxSize( unsigned byteCount ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif + protected: std::shared_ptr sourceBuffer_; uint64_t currentRecordIndex_; diff --git a/src/3rdParty/libE57Format/src/FloatNode.cpp b/src/3rdParty/libE57Format/src/FloatNode.cpp new file mode 100644 index 0000000000000..b6ed72ddc8487 --- /dev/null +++ b/src/3rdParty/libE57Format/src/FloatNode.cpp @@ -0,0 +1,361 @@ +/* + * FloatNode.cpp - implementation of public functions of the FloatNode class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file FloatNode.cpp + +#include "FloatNodeImpl.h" +#include "StringFunctions.h" + +using namespace e57; + +// Putting this function first so we can reference the code in doxygen using @skip +/// @brief Check whether FloatNode class invariant is true +/// @copydetails IntegerNode::checkInvariant() +void FloatNode::checkInvariant( bool /*doRecurse*/, bool doUpcast ) const +{ + // If destImageFile not open, can't test invariant (almost every call would throw) + if ( !destImageFile().isOpen() ) + { + return; + } + + // If requested, call Node::checkInvariant + if ( doUpcast ) + { + static_cast( *this ).checkInvariant( false, false ); + } + + if ( precision() == PrecisionSingle ) + { + if ( static_cast( minimum() ) < FLOAT_MIN || + static_cast( maximum() ) > FLOAT_MAX ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + + // If value is out of bounds + if ( value() < minimum() || value() > maximum() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } +} + +/*! +@class e57::FloatNode + +@brief An E57 element encoding a single or double precision IEEE floating point number. + +@details +An FloatNode is a terminal node (i.e. having no children) that holds an IEEE floating point value, +and minimum/maximum bounds. The precision of the floating point value and attributes may be either +single or double precision. Once the FloatNode value and attributes are set at creation, they may +not be modified. + +If the precision option of the FloatNode is Single: +The minimum attribute may be a number in the interval [-3.402823466e+38, 3.402823466e+38]. The +maximum attribute may be a number in the interval [maximum, 3.402823466e+38]. The value may be a +number in the interval [minimum, maximum]. + +If the precision option of the FloatNode is Double: +The minimum attribute may be a number in the interval +[-1.7976931348623158e+308, 1.7976931348623158e+308]. The maximum attribute may be a number in the +interval [maximum, 1.7976931348623158e+308]. The value may be a number in the interval [minimum, +maximum]. + +See Node class discussion for discussion of the common functions that StructureNode supports. + +@section FloatNode_invariant Class Invariant +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude FloatNode.cpp +@skip void FloatNode::checkInvariant +@until ^} + +@see Node +*/ + +/*! +@brief Create an E57 element for storing an double precision IEEE floating point number. + +@param [in] destImageFile The ImageFile where the new node will eventually be stored. +@param [in] value The double precision IEEE floating point value of the element. +@param [in] precision The precision of IEEE floating point to use. May be ::PrecisionSingle or +::PrecisionDouble. +@param [in] minimum The smallest value that the value may take. +@param [in] maximum The largest value that the value may take. + +@details +An FloatNode stores an IEEE floating point number and a lower and upper bound. The FloatNode class +corresponds to the ASTM E57 standard Float element. See the class discussion at bottom of FloatNode +page for more details. + +The @a destImageFile indicates which ImageFile the FloatNode will eventually be attached to. A node +is attached to an ImageFile by adding it underneath the predefined root of the ImageFile (gotten +from ImageFile::root). It is not an error to fail to attach the FloatNode to the @a destImageFile. +It is an error to attempt to attach the FloatNode to a different ImageFile. + +There is only one FloatNode constructor that handles both ::PrecisionSingle and ::PrecisionDouble +precision cases. If @a precision = ::PrecisionSingle, then the object will silently round the double +precision @a value to the nearest representable single precision value. In this case, the lower bits +will be lost, and if the value is outside the representable range of a single precision number, the +exponent may be changed. The same is true for the @a minimum and @a maximum arguments. + +@warning It is an error to give an @a value outside the @a minimum / @a maximum bounds, even if the +FloatNode is destined to be used in a CompressedVectorNode prototype (where the @a value will be +ignored). If the FloatNode is to be used in a prototype, it is recommended to specify a @a value = 0 +if 0 is within bounds, or a @a value = @a minimum if 0 is not within bounds. + +@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be true). +@pre The @a destImageFile must have been opened in write mode (i.e. destImageFile.isWritable() must +be true). +@pre minimum <= value <= maximum + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorFileReadOnly +@throw ::ErrorValueOutOfBounds +@throw ::ErrorInternal All objects in undocumented state + +@see FloatPrecision, FloatNode::value, Node, CompressedVectorNode, CompressedVectorNode::prototype +*/ +FloatNode::FloatNode( const ImageFile &destImageFile, double value, FloatPrecision precision, + double minimum, double maximum ) : + impl_( new FloatNodeImpl( destImageFile.impl(), value, true, precision, minimum, maximum ) ) +{ +} + +/*! +@brief Is this a root node. +@copydetails Node::isRoot() +*/ +bool FloatNode::isRoot() const +{ + return impl_->isRoot(); +} + +/*! +@brief Return parent of node, or self if a root node. +@copydetails Node::parent() +*/ +Node FloatNode::parent() const +{ + return Node( impl_->parent() ); +} + +/*! +@brief Get absolute pathname of node. +@copydetails Node::pathName() +*/ +ustring FloatNode::pathName() const +{ + return impl_->pathName(); +} + +/*! +@brief Get elementName string, that identifies the node in its parent. +@copydetails Node::elementName() +*/ +ustring FloatNode::elementName() const +{ + return impl_->elementName(); +} + +/*! +@brief Get the ImageFile that was declared as the destination for the node when it was created. +@copydetails Node::destImageFile() +*/ +ImageFile FloatNode::destImageFile() const +{ + return ImageFile( impl_->destImageFile() ); +} + +/*! +@brief Has node been attached into the tree of an ImageFile. +@copydetails Node::isAttached() +*/ +bool FloatNode::isAttached() const +{ + return impl_->isAttached(); +} + +/*! +@brief Get IEEE floating point value stored. + +@details +If precision is ::PrecisionSingle, the single precision value is returned as a double. If precision +is ::PrecisionDouble, the double precision value is returned as a double. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The IEEE floating point value stored, represented as a double. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see FloatNode::minimum, FloatNode::maximum +*/ +double FloatNode::value() const +{ + return impl_->value(); +} + +/*! +@brief Get declared precision of the floating point number. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The declared precision of the floating point number, either ::PrecisionSingle or +::PrecisionDouble. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see FloatPrecision +*/ +FloatPrecision FloatNode::precision() const +{ + return impl_->precision(); +} + +/*! +@brief Get the declared minimum that the value may take. + +@details +If precision is ::PrecisionSingle, the single precision minimum is returned as a double. If +precision is ::PrecisionDouble, the double precision minimum is returned as a double. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The declared minimum that the value may take. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see FloatNode::maximum, FloatNode::value +*/ +double FloatNode::minimum() const +{ + return impl_->minimum(); +} + +/*! +@brief Get the declared maximum that the value may take. + +@details +If precision is ::PrecisionSingle, the single precision maximum is returned as a double. If +precision is ::PrecisionDouble, the double precision maximum is returned as a double. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The declared maximum that the value may take. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see FloatNode::minimum, FloatNode::value +*/ +double FloatNode::maximum() const +{ + return impl_->maximum(); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void FloatNode::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void FloatNode::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif + +/*! +@brief Upcast a FloatNode handle to a generic Node handle. + +@details An upcast is always safe, and the compiler can automatically insert it for initializations +of Node variables and Node function arguments. + +@return A smart Node handle referencing the underlying object. + +@throw No E57Exceptions. + +@see Explanation in Node, Node::type() +*/ +FloatNode::operator Node() const +{ + // Upcast from shared_ptr to SharedNodeImplPtr and construct a Node object + return Node( impl_ ); +} + +/*! +@brief Downcast a generic Node handle to a FloatNode handle. + +@param [in] n The generic handle to downcast. + +@details +The handle @a n must be for an underlying FloatNode, otherwise an exception is thrown. In designs +that need to avoid the exception, use Node::type() to determine the actual type of the @a n before +downcasting. This function must be explicitly called (c++ compiler cannot insert it automatically). + +@throw ::ErrorBadNodeDowncast + +@see Node::type(), FloatNode::operator Node() +*/ +FloatNode::FloatNode( const Node &n ) +{ + if ( n.type() != TypeFloat ) + { + throw E57_EXCEPTION2( ErrorBadNodeDowncast, "nodeType=" + toString( n.type() ) ); + } + + // Set our shared_ptr to the downcast shared_ptr + impl_ = std::static_pointer_cast( n.impl() ); +} + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +FloatNode::FloatNode( std::shared_ptr ni ) : impl_( ni ) +{ +} +/// @endcond diff --git a/src/3rdParty/libE57Format/src/FloatNodeImpl.cpp b/src/3rdParty/libE57Format/src/FloatNodeImpl.cpp index 7bdb15fa45a6a..0319b0719e395 100644 --- a/src/3rdParty/libE57Format/src/FloatNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/FloatNodeImpl.cpp @@ -27,37 +27,38 @@ #include "FloatNodeImpl.h" #include "CheckedFile.h" +#include "StringFunctions.h" namespace e57 { - FloatNodeImpl::FloatNodeImpl( ImageFileImplWeakPtr destImageFile, double value, FloatPrecision precision, - double minimum, double maximum ) : + FloatNodeImpl::FloatNodeImpl( ImageFileImplWeakPtr destImageFile, double value, bool validValue, + FloatPrecision precision, double minimum, double maximum ) : NodeImpl( destImageFile ), value_( value ), precision_( precision ), minimum_( minimum ), maximum_( maximum ) { // don't checkImageFileOpen, NodeImpl() will do it - /// Since this ctor also used to construct single precision, and defaults for - /// minimum/maximum are for double precision, adjust bounds smaller if - /// single. - if ( precision_ == E57_SINGLE ) + // Since this ctor also used to construct single precision, and defaults for minimum/maximum + // are for double precision, adjust bounds smaller if single. + if ( precision_ == PrecisionSingle ) { - if ( minimum_ < E57_FLOAT_MIN ) + if ( minimum_ < FLOAT_MIN ) { - minimum_ = E57_FLOAT_MIN; + minimum_ = FLOAT_MIN; } - if ( maximum_ > E57_FLOAT_MAX ) + if ( maximum_ > FLOAT_MAX ) { - maximum_ = E57_FLOAT_MAX; + maximum_ = FLOAT_MAX; } } - /// Enforce the given bounds on raw value - if ( value < minimum || maximum < value ) + // Enforce the given bounds on raw value if it is valid + if ( validValue && ( value < minimum || value > maximum ) ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_OUT_OF_BOUNDS, - "this->pathName=" + this->pathName() + " value=" + toString( value ) + - " minimum=" + toString( minimum ) + " maximum=" + toString( maximum ) ); + throw E57_EXCEPTION2( ErrorValueOutOfBounds, "this->pathName=" + this->pathName() + + " value=" + toString( value ) + + " minimum=" + toString( minimum ) + + " maximum=" + toString( maximum ) ); } } @@ -65,36 +66,36 @@ namespace e57 { // don't checkImageFileOpen - /// Same node type? - if ( ni->type() != E57_FLOAT ) + // Same node type? + if ( ni->type() != TypeFloat ) { return ( false ); } - /// Downcast to shared_ptr + // Downcast to shared_ptr std::shared_ptr fi( std::static_pointer_cast( ni ) ); - /// precision must match + // precision must match if ( precision_ != fi->precision_ ) { return ( false ); } - /// minimum must match + // minimum must match if ( minimum_ != fi->minimum_ ) { return ( false ); } - /// maximum must match + // maximum must match if ( maximum_ != fi->maximum_ ) { return ( false ); } - /// ignore value_, doesn't have to match + // ignore value_, doesn't have to match - /// Types match + // Types match return ( true ); } @@ -102,7 +103,7 @@ namespace e57 { // don't checkImageFileOpen - /// We have no sub-structure, so if path not empty return false + // We have no sub-structure, so if path not empty return false return pathName.empty(); } @@ -134,12 +135,11 @@ namespace e57 { // don't checkImageFileOpen - /// We are a leaf node, so verify that we are listed in set (either relative - /// or absolute form) + // We are a leaf node, so verify that we are listed in set (either relative or absolute form) if ( pathNames.find( relativePathName( origin ) ) == pathNames.end() && pathNames.find( pathName() ) == pathNames.end() ) { - throw E57_EXCEPTION2( E57_ERROR_NO_BUFFER_FOR_ELEMENT, "this->pathName=" + this->pathName() ); + throw E57_EXCEPTION2( ErrorNoBufferForElement, "this->pathName=" + this->pathName() ); } } @@ -149,7 +149,7 @@ namespace e57 // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName ) + if ( forcedFieldName != nullptr ) { fieldName = forcedFieldName; } @@ -159,21 +159,21 @@ namespace e57 } cf << space( indent ) << "<" << fieldName << " type=\"Float\""; - if ( precision_ == E57_SINGLE ) + if ( precision_ == PrecisionSingle ) { cf << " precision=\"single\""; - /// Don't need to write if are default values - if ( minimum_ > E57_FLOAT_MIN ) + // Don't need to write if are default values + if ( minimum_ > FLOAT_MIN ) { cf << " minimum=\"" << static_cast( minimum_ ) << "\""; } - if ( maximum_ < E57_FLOAT_MAX ) + if ( maximum_ < FLOAT_MAX ) { cf << " maximum=\"" << static_cast( maximum_ ) << "\""; } - /// Write value as child text, unless it is the default value + // Write value as child text, unless it is the default value if ( value_ != 0.0 ) { cf << ">" << static_cast( value_ ) << "\n"; @@ -185,19 +185,19 @@ namespace e57 } else { - /// Don't need to write precision="double", because that's the default + // Don't need to write precision="double", because that's the default - /// Don't need to write if are default values - if ( minimum_ > E57_DOUBLE_MIN ) + // Don't need to write if are default values + if ( minimum_ > DOUBLE_MIN ) { cf << " minimum=\"" << minimum_ << "\""; } - if ( maximum_ < E57_DOUBLE_MAX ) + if ( maximum_ < DOUBLE_MAX ) { cf << " maximum=\"" << maximum_ << "\""; } - /// Write value as child text, unless it is the default value + // Write value as child text, unless it is the default value if ( value_ != 0.0 ) { cf << ">" << value_ << "\n"; @@ -209,7 +209,7 @@ namespace e57 } } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void FloatNodeImpl::dump( int indent, std::ostream &os ) const { // don't checkImageFileOpen @@ -217,7 +217,7 @@ namespace e57 << " (" << type() << ")" << std::endl; NodeImpl::dump( indent, os ); os << space( indent ) << "precision: "; - if ( precision() == E57_SINGLE ) + if ( precision() == PrecisionSingle ) { os << "single" << std::endl; } @@ -226,15 +226,16 @@ namespace e57 os << "double" << std::endl; } - /// Save old stream config + // Save old stream config const std::streamsize oldPrecision = os.precision(); const std::ios_base::fmtflags oldFlags = os.flags(); - os << space( indent ) << std::scientific << std::setprecision( 17 ) << "value: " << value_ << std::endl; + os << space( indent ) << std::scientific << std::setprecision( 17 ) + << "value: " << value_ << std::endl; os << space( indent ) << "minimum: " << minimum_ << std::endl; os << space( indent ) << "maximum: " << maximum_ << std::endl; - /// Restore old stream config + // Restore old stream config os.precision( oldPrecision ); os.flags( oldFlags ); } diff --git a/src/3rdParty/libE57Format/src/FloatNodeImpl.h b/src/3rdParty/libE57Format/src/FloatNodeImpl.h index 67b0be5d34869..a479ecd6fef9f 100644 --- a/src/3rdParty/libE57Format/src/FloatNodeImpl.h +++ b/src/3rdParty/libE57Format/src/FloatNodeImpl.h @@ -33,14 +33,16 @@ namespace e57 class FloatNodeImpl : public NodeImpl { public: - FloatNodeImpl( ImageFileImplWeakPtr destImageFile, double value = 0, FloatPrecision precision = E57_DOUBLE, - double minimum = E57_DOUBLE_MIN, double maximum = E57_DOUBLE_MAX ); + explicit FloatNodeImpl( ImageFileImplWeakPtr destImageFile, double value = 0, + bool validValue = true, FloatPrecision precision = PrecisionDouble, + double minimum = DOUBLE_MIN, double maximum = DOUBLE_MAX ); ~FloatNodeImpl() override = default; NodeType type() const override { - return E57_FLOAT; + return TypeFloat; } + bool isTypeEquivalent( NodeImplSharedPtr ni ) override; bool isDefined( const ustring &pathName ) override; @@ -54,7 +56,7 @@ namespace e57 void writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, const char *forcedFieldName = nullptr ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif diff --git a/src/3rdParty/libE57Format/src/ImageFile.cpp b/src/3rdParty/libE57Format/src/ImageFile.cpp new file mode 100644 index 0000000000000..11bf0fb8fadc7 --- /dev/null +++ b/src/3rdParty/libE57Format/src/ImageFile.cpp @@ -0,0 +1,771 @@ +/* + * ImageFile.cpp - implementation of public functions of the ImageFile class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file ImageFile.cpp + +#include "ImageFileImpl.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/*! +@brief Check whether ImageFile class invariant is true + +@param [in] doRecurse If true, also check invariants of all children or sub-objects recursively. + +@details +This function checks at least the assertions in the documented class invariant description (see +class reference page for this object). Other internal invariants that are implementation-dependent +may also be checked. If any invariant clause is violated, an E57Exception with errorCode of +ErrorInvarianceViolation is thrown. + +Checking the invariant recursively may be expensive if the tree is large, so should be used +judiciously, in debug versions of the application. + +@post No visible state is modified. + +@throw ::ErrorInvarianceViolation or any other E57 ErrorCode + +@see Node::checkInvariant +*/ +void ImageFile::checkInvariant( bool doRecurse ) const +{ + // If this ImageFile is not open, can't test invariant (almost every call + // would throw) + if ( !isOpen() ) + { + return; + } + + // root() node must be a root node + if ( !root().isRoot() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Can't have empty fileName + if ( fileName().empty() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + int wCount = writerCount(); + int rCount = readerCount(); + + // Can't have negative number of readers + if ( rCount < 0 ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Can't have negative number of writers + if ( wCount < 0 ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Can't have more than one writer + if ( 1 < wCount ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // If have writer + if ( wCount > 0 ) + { + // Must be in write-mode + if ( !isWritable() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Can't have any readers + if ( rCount > 0 ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + + // Extension prefixes and URIs are unique + const size_t eCount = extensionsCount(); + for ( size_t i = 0; i < eCount; i++ ) + { + for ( size_t j = i + 1; j < eCount; j++ ) + { + if ( extensionsPrefix( i ) == extensionsPrefix( j ) ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + if ( extensionsUri( i ) == extensionsUri( j ) ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + } + + // Verify lookup functions are correct + for ( size_t i = 0; i < eCount; i++ ) + { + ustring goodPrefix = extensionsPrefix( i ); + ustring goodUri = extensionsUri( i ); + ustring prefix; + ustring uri; + if ( !extensionsLookupPrefix( goodPrefix, uri ) ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + if ( uri != goodUri ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + if ( !extensionsLookupUri( goodUri, prefix ) ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + if ( prefix != goodPrefix ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + + // If requested, check all objects "below" this one + if ( doRecurse ) + { + root().checkInvariant( doRecurse ); + } +} + +/*! +@class e57::ImageFile + +@brief An ASTM E57 3D format file object. + +@details +@section imagefile_ClassOverview Class overview +The ImageFile class represents the state of an ASTM E57 format data file. An ImageFile may be +created from an E57 file on the disk (read mode). An new ImageFile may be created to write an E57 +file to disk (write mode). + +E57 files are organized in a tree structure. +Each ImageFile object has a predefined root node (of type StructureNode). In a write mode ImageFile, +the root node is initially empty. In a read mode ImageFile, the root node is populated by the tree +stored in the .e57 file on disk. + +@section imagefile_OpenClose The open/close state +An ImageFile object, opened in either mode (read/write), can be in one of two states: open or +closed. An ImageFile in the open state is ready to perform transfers of data and to be interrogated. +An ImageFile in the closed state cannot perform any further transfers, and has very limited ability +to be interrogated. Note entering the closed state is different than destroying the ImageFile +object. An ImageFile object can still exist and be in the closed state. When created, the ImageFile +is initially open. + +The ImageFile state can transition to the closed state in two ways. The programmer can call +ImageFile::close after all required processing has completed. The programmer can call +ImageFile::cancel if it is determined that the ImageFile is no longer needed. + +@section imagefile_Extensions Extensions +Basically in an E57 file, "extension = namespace + rules + meaning". +The "namespace" ensures that element names don't collide. +The "rules" may be written on paper, or partly codified in a computer grammar. +The "meaning" is a definition of what was measured, what the numbers in the file mean. + +Extensions are identified by URIs. +Extensions are not identified by prefixes. +Prefixes are a shorthand, used in a particular file, to make the element names more palatable for +humans. When thinking about a prefixed element name, in your mind you should immediately substitute +the URI for the prefix. For example, think "http://www.example.com/DemoExtension:extra2" rather than +"demo:extra2", if the prefix "demo" is declared in the file to be a shorthand for the URI +"http://www.example.com/DemoExtension". + +The rules are statements of: what is valid, what element names are possible, what values are +possible. The rules establish the answer to the following yes/no question: "Is this extended E57 +file valid?". The rules divide all possible files into two sets: valid files and invalid files. + +The "meanings" part of the above equation defines what the files in the first set, the valid files, +actually mean. This definition usually comes in the form of documentation of the content of each new +element in the format and how they relate to the other elements. + +An element name in an E57 file is a member of exactly one namespace (either the default namespace +defined in the ASTM standard, or an extension namespace). Rules about the structure of an E57 +extension (what element names can appear where), are implicitly assumed only to govern the element +names within the namespace of the extension. Element names in other namespaces are unconstrained. +This is because a reader is required to ignore elements in namespaces that are unfamiliar (to treat +them as if they didn't exist). This enables a writer to "tack on" new elements into pre-defined +structures (e.g. structures defined in the ASTM standard), without fear that it will confuse a +reader that is only familiar with the old format. This allows an extension designer to communicate +to two sets of readers: the old readers that will understand the information in the old base format, +and the new-fangled readers that will be able to read the base format and the extra information +stored in element names in the extended namespace. + +@section ImageFile_invariant Class Invariant +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude ImageFile.cpp +@skip void ImageFile::checkInvariant +@until ^} +*/ + +/*! +@brief Open an ASTM E57 imaging data file for reading/writing. + +@param [in] fname File name to open. +Support of '\' as a directory separating character is system dependent. For maximum portability, it +is recommended that '/' be used as a directory separator in file names. Special device file name +support are implementation dependent (e.g. "\\.\PhysicalDrive3" or "/dev/hd3"). It is recommended +that files that meet all of the requirements for a legal ASTM E57 file format use the extension @c +".e57". It is recommended that files that utilize the low-level E57 element data types, but do not +have all the required element names required by ASTM E57 file format standard use the file extension +@c "._e57". +@param [in] mode Either "w" for writing or "r" for reading. +@param [in] checksumPolicy The percentage of checksums we compute and verify as an int. Clamped to +0-100. + +@par Write Mode +In write mode, the file cannot be already open. +A file with name given by @a fname is immediately created on the disk. +This file may grow as a result of operations on the ImageFile. +Which API functions write data to the file are implementation dependent. +Thus any API operation that stores data may fail as a result of insufficient free disk space. Read +API operations are legal for an ImageFile opened in write mode. + +@par Read Mode +Read mode files may be shared. +Write API operations are not legal for an ImageFile opened in read mode (i.e. the ImageFile is +read-only). There is no API support for appending data onto an existing E57 data file. + +@post Resulting ImageFile is in @c open state if constructor succeeds (no exception thrown). + +@throw ::ErrorBadAPIArgument +@throw ::ErrorOpenFailed +@throw ::ErrorSeekFailed +@throw ::ErrorReadFailed +@throw ::ErrorWriteFailed +@throw ::ErrorBadChecksum +@throw ::ErrorBadFileSignature +@throw ::ErrorUnknownFileVersion +@throw ::ErrorBadFileLength +@throw ::ErrorXMLParserInit +@throw ::ErrorXMLParser +@throw ::ErrorBadXMLFormat +@throw ::ErrorBadConfiguration +@throw ::ErrorInternal All objects in undocumented state + +@see IntegerNode, ScaledIntegerNode, FloatNode, StringNode, BlobNode, StructureNode, VectorNode, +CompressedVectorNode, E57Exception, E57Utilities::E57Utilities +*/ +ImageFile::ImageFile( const ustring &fname, const ustring &mode, + ReadChecksumPolicy checksumPolicy ) : + impl_( new ImageFileImpl( checksumPolicy ) ) +{ + // Do second phase of construction, now that ImageFile object is complete. + impl_->construct2( fname, mode ); +} + +ImageFile::ImageFile( const char *input, const uint64_t size, ReadChecksumPolicy checksumPolicy ) : + impl_( new ImageFileImpl( checksumPolicy ) ) +{ + impl_->construct2( input, size ); +} + +/*! +@brief Get the pre-established root StructureNode of the E57 ImageFile. + +@details The root node of an ImageFile always exists and is always type StructureNode. The root node +is empty in a newly created write mode ImageFile. + +@pre This ImageFile must be open (i.e. isOpen()). + +@return A smart StructureNode handle referencing the underlying object. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see StructureNode. +*/ +StructureNode ImageFile::root() const +{ + return StructureNode( impl_->root() ); +} + +/*! +@brief Complete any write operations on an ImageFile, and close the file on the disk. + +@details +Completes the writing of the state of the ImageFile to the disk. +Some API implementations may store significant portions of the state of the ImageFile in memory. +This state is moved into the disk file before it is closed. Any errors in finishing the writing are +reported by throwing an exception. If an exception is thrown, depending on the error code, the +ImageFile may enter the closed state. If no exception is thrown, then the file on disk will be an +accurate representation of the ImageFile. + +@warning If the ImageFile::close function is not called, and the ImageFile destructor is invoked +with the ImageFile in the open state, the associated disk file will be deleted and the ImageFile +will @em not be saved to the disk (the same outcome as calling ImageFile::cancel). The reason for +this is that any error conditions can't be reported from a destructor, so the user can't be assured +that the destruction/close completed successfully. It is strongly recommended that this close +function be called before the ImageFile is destroyed. + +It is not an error if ImageFile is already closed. + +@post ImageFile is in @c closed state. + +@throw ::ErrorSeekFailed +@throw ::ErrorReadFailed +@throw ::ErrorWriteFailed +@throw ::ErrorCloseFailed +@throw ::ErrorBadChecksum +@throw ::ErrorInternal All objects in undocumented state + +@see ImageFile::cancel, ImageFile::isOpen +*/ +void ImageFile::close() +{ + impl_->close(); +} + +/*! +@brief Stop I/O operations and delete a partially written ImageFile on the disk. + +@details +If the ImageFile is write mode, the associated file on the disk is closed and deleted, and the +ImageFile goes to the closed state. If the ImageFile is read mode, the behavior is same as calling +ImageFile::close, but no exceptions are thrown. It is not an error if ImageFile is already closed. + +@post ImageFile is in @c closed state. + +@throw No E57Exceptions. + +@see ImageFile::ImageFile, ImageFile::close, ImageFile::isOpen +*/ +void ImageFile::cancel() +{ + impl_->cancel(); +} + +/*! +@brief Test whether ImageFile is still open for accessing. + +@post No visible state is modified. + +@return true if ImageFile is in @c open state. + +@throw No E57Exceptions. + +@see ImageFile::ImageFile, ImageFile::close +*/ +bool ImageFile::isOpen() const +{ + return impl_->isOpen(); +} + +/*! +@brief Test whether ImageFile was opened in write mode. + +@post No visible state is modified. + +@return true if ImageFile was opened in write mode. + +@throw No E57Exceptions. + +@see ImageFile::ImageFile, ImageFile::isOpen +*/ +bool ImageFile::isWritable() const +{ + return impl_->isWriter(); +} + +/*! +@brief Get the file name the ImageFile was created with. + +@post No visible state is modified. + +@return The file name the ImageFile was created with. + +@throw No E57Exceptions. + +@see ImageFile::ImageFile +*/ +ustring ImageFile::fileName() const +{ + return impl_->fileName(); +} + +/*! +@brief Get current number of open CompressedVectorWriter objects writing to ImageFile. + +@details +CompressedVectorWriter objects that still exist, but are in the closed state aren't counted. +CompressedVectorWriter objects are created by the CompressedVectorNode::writer function. + +@pre This ImageFile must be open (i.e. isOpen()). +@post No visible state is modified. + +@return The current number of open CompressedVectorWriter objects writing to ImageFile. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorNode::writer, CompressedVectorWriter +*/ +int ImageFile::writerCount() const +{ + return impl_->writerCount(); +} + +/*! +@brief Get current number of open CompressedVectorReader objects reading from ImageFile. + +@details +CompressedVectorReader objects that still exist, but are in the closed state aren't counted. +CompressedVectorReader objects are created by the CompressedVectorNode::reader function. + +@pre This ImageFile must be open (i.e. isOpen()). +@post No visible state is modified. + +@return The current number of open CompressedVectorReader objects reading from ImageFile. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVectorNode::reader, CompressedVectorReader +*/ +int ImageFile::readerCount() const +{ + return impl_->readerCount(); +} + +/*! +@brief Declare the use of an E57 extension in an ImageFile being written. + +@param [in] prefix The shorthand name of the extension to use in element names. +@param [in] uri The Uniform Resource Identifier string to associate with the prefix in the +ImageFile. + +@details +The (@a prefix, @a uri) pair is registered in the known extensions of the ImageFile. Both @a prefix +and @a uri must be unique in the ImageFile. It is not legal to declare a URI associated with the +default namespace (@a prefix = ""). It is not an error to declare a namespace and not use it in an +element name. It is an error to use a namespace prefix in an element name that is not declared +beforehand. + +A writer is free to "hard code" the prefix names in the element name strings that it uses (since it +established the prefix declarations in the file). A reader cannot assume that any given prefix is +always mapped to the same URI or vice versa. A reader might check an ImageFile, and if the prefixes +aren't the way it likes, the reader could give up. + +A better scheme would be to lookup the URI that the reader is familiar with, and store the prefix +that the particular file uses in a variable. Then every time the reader needs to form a prefixed +element name, it can assemble the full element name from the stored prefix variable and the constant +documented base name string. This is less convenient than using a single "hard coded" string +constant for an element name, but it is robust against any choice of prefix/URI combination. + +See the class discussion at bottom of ImageFile page for more details about namespaces. + +@pre This ImageFile must be open (i.e. isOpen()). +@pre ImageFile must have been opened in write mode (i.e. isWritable()). +@pre prefix != "" +@pre uri != "" + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorFileReadOnly +@throw ::ErrorDuplicateNamespacePrefix +@throw ::ErrorDuplicateNamespaceURI +@throw ::ErrorInternal All objects in undocumented state + +@see ImageFile::extensionsCount, ImageFile::extensionsLookupPrefix, ImageFile::extensionsLookupUri +*/ +void ImageFile::extensionsAdd( const ustring &prefix, const ustring &uri ) +{ + impl_->extensionsAdd( prefix, uri ); +} + +/*! +@brief Look up an E57 extension prefix in the ImageFile. + +@param [in] prefix The shorthand name of the extension to look up. + +@details +If @a prefix = "" or @a prefix is declared in the ImageFile, then the function returns true. It is +an error if @a prefix contains an illegal character combination for E57 namespace prefixes. + +@pre This ImageFile must be open (i.e. isOpen()). +@post No visible state is modified. + +@return true if prefix is declared in the ImageFile. + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ImageFile::extensionsLookupUri +*/ +bool ImageFile::extensionsLookupPrefix( const ustring &prefix ) const +{ + ustring uri; + return impl_->extensionsLookupPrefix( prefix, uri ); +} + +/*! +@brief Get URI associated with an E57 extension prefix in the ImageFile. + +@param [in] prefix The shorthand name of the extension to look up. +@param [out] uri The URI that was associated with the given @a prefix. + +@details +If @a prefix = "", then @a uri is set to the default namespace URI, and the function returns true. +if @a prefix is declared in the ImageFile, then @a uri is set the corresponding URI, and the +function returns true. It is an error if @a prefix contains an illegal character combination for E57 +namespace prefixes. It is not an error if @a prefix is well-formed, but not defined in the ImageFile +(the function just returns false). + +@pre This ImageFile must be open (i.e. isOpen()). +@post No visible state is modified. + +@return true if prefix is declared in the ImageFile. + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen + +@throw ::ErrorInternal All objects in undocumented state + +@see ImageFile::extensionsLookupUri +*/ +bool ImageFile::extensionsLookupPrefix( const ustring &prefix, ustring &uri ) const +{ + return impl_->extensionsLookupPrefix( prefix, uri ); +} + +/*! +@brief Get an E57 extension prefix associated with a URI in the ImageFile. + +@param [in] uri The URI of the extension to look up. +@param [out] prefix The shorthand prefix that was associated with the given @a uri. + +@details +If @a uri is declared in the ImageFile, then @a prefix is set the corresponding prefix, and the +function returns true. It is an error if @a uri contains an illegal character combination for E57 +namespace URIs. It is not an error if @a uri is well-formed, but not defined in the ImageFile (the +function just returns false). + +@pre This ImageFile must be open (i.e. isOpen()). +@pre uri != "" +@post No visible state is modified. + +@return true if URI is declared in the ImageFile. + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ImageFile::extensionsLookupPrefix +*/ +bool ImageFile::extensionsLookupUri( const ustring &uri, ustring &prefix ) const +{ + return impl_->extensionsLookupUri( uri, prefix ); +} + +/*! +@brief Get number of E57 extensions declared in the ImageFile. + +@details +The default E57 namespace does not count as an extension. + +@pre This ImageFile must be open (i.e. isOpen()). +@post No visible state is modified. + +@return The number of E57 extensions defined in the ImageFile. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ImageFile::extensionsPrefix, ImageFile::extensionsUri +*/ +size_t ImageFile::extensionsCount() const +{ + return impl_->extensionsCount(); +} + +/*! +@brief Get an E57 extension prefix declared in an ImageFile by index. + +@param [in] index The index of the prefix to get, starting at 0. + +@details +The order that the prefixes are stored in is not necessarily the same as the order they were +created. However the prefix order will correspond to the URI order. The default E57 namespace is not +counted as an extension. + +@pre This ImageFile must be open (i.e. isOpen()). +@pre 0 <= index < extensionsCount() +@post No visible state is modified. + +@return The E57 extension prefix at the given index. + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ImageFile::extensionsCount, ImageFile::extensionsUri +*/ +ustring ImageFile::extensionsPrefix( const size_t index ) const +{ + return impl_->extensionsPrefix( index ); +} + +/*! +@brief Get an E57 extension URI declared in an ImageFile by index. + +@param [in] index The index of the URI to get, starting at 0. + +@details +The order that the URIs are stored is not necessarily the same as the order they were created. +However the URI order will correspond to the prefix order. The default E57 namespace is not counted +as an extension. + +@pre This ImageFile must be open (i.e. isOpen()). +@pre 0 <= index < extensionsCount() +@post No visible state is modified. + +@return The E57 extension URI at the given index. + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ImageFile::extensionsCount, ImageFile::extensionsPrefix +*/ +ustring ImageFile::extensionsUri( const size_t index ) const +{ + return impl_->extensionsUri( index ); +} + +/*! +@brief Test whether an E57 element name has an extension prefix. + +@details +The element name has a prefix if the function elementNameParse(elementName,prefix,dummy) would +succeed, and returned prefix != "". + +@param [in] elementName The string element name to test. + +@post No visible state is modified. + +@return True if the E57 element name has an extension prefix. + +@throw No E57Exceptions. +*/ +bool ImageFile::isElementNameExtended( const ustring &elementName ) const +{ + return impl_->isElementNameExtended( elementName ); +} + +/*! +@brief Parse element name into prefix and localPart substrings. + +@param [in] elementName The string element name to parse into prefix and local parts. +@param [out] prefix The prefix (if any) in the @a elementName. +@param [out] localPart The part of the element name after the prefix. + +@details +A legal element name may be in prefixed (ID:ID) or unprefixed (ID) form, where ID is a string whose +first character is in {a-z,A-Z,_} followed by zero or more characters in {a-z,A-Z,_,0-9,-,.}. If in +prefixed form, the prefix does not have to be declared in the ImageFile. + +@post No visible state is modified. + +@throw ::ErrorBadPathName +@throw ::ErrorInternal All objects in undocumented state + +@see ImageFile::isElementNameExtended +*/ +void ImageFile::elementNameParse( const ustring &elementName, ustring &prefix, + ustring &localPart ) const +{ + impl_->elementNameParse( elementName, prefix, localPart ); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void ImageFile::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void ImageFile::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif + +/*! +@brief Test if two ImageFile handles refer to the same underlying ImageFile + +@param [in] imf2 The ImageFile to compare this ImageFile with + +@post No visible object state is modified. + +@return @c true if ImageFile handles refer to the same underlying ImageFile. + +@throw No E57Exceptions +*/ +bool ImageFile::operator==( const ImageFile &imf2 ) const +{ + return ( impl_ == imf2.impl_ ); +} + +/*! +@brief Test if two ImageFile handles refer to different underlying ImageFile + +@param [in] imf2 The ImageFile to compare this ImageFile with + +@post No visible object state is modified. + +@return @c true if ImageFile handles refer to different underlying ImageFiles. + +@throw No E57Exceptions +*/ +bool ImageFile::operator!=( const ImageFile &imf2 ) const +{ + return ( impl_ != imf2.impl_ ); +} + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +ImageFile::ImageFile( ImageFileImplSharedPtr imfi ) : impl_( imfi ) +{ +} +/// @endcond diff --git a/src/3rdParty/libE57Format/src/ImageFileImpl.cpp b/src/3rdParty/libE57Format/src/ImageFileImpl.cpp index fbc9c5924efd4..6299a445c598e 100644 --- a/src/3rdParty/libE57Format/src/ImageFileImpl.cpp +++ b/src/3rdParty/libE57Format/src/ImageFileImpl.cpp @@ -26,9 +26,10 @@ */ #include "ImageFileImpl.h" +#include "ASTMVersion.h" #include "CheckedFile.h" -#include "E57Version.h" #include "E57XmlParser.h" +#include "StringFunctions.h" #include "StructureNodeImpl.h" namespace e57 @@ -52,14 +53,13 @@ namespace e57 uint64_t xmlPhysicalOffset = 0; uint64_t xmlLogicalLength = 0; uint64_t pageSize = 0; - // char e57LibraryVersion[8]; //Not in V1.0 Standard -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const; #endif }; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void E57FileHeader::dump( int indent, std::ostream &os ) const { os << space( indent ) << "fileSignature: "; @@ -76,24 +76,24 @@ namespace e57 ImageFileImpl::ImageFileImpl( ReadChecksumPolicy policy ) : isWriter_( false ), writerCount_( 0 ), readerCount_( 0 ), - checksumPolicy( std::max( 0, std::min( policy, 100 ) ) ), file_( nullptr ), xmlLogicalOffset_( 0 ), - xmlLogicalLength_( 0 ), unusedLogicalStart_( 0 ) + checksumPolicy( std::max( 0, std::min( policy, 100 ) ) ), file_( nullptr ), + xmlLogicalOffset_( 0 ), xmlLogicalLength_( 0 ), unusedLogicalStart_( 0 ) { - /// First phase of construction, can't do much until have the ImageFile - /// object. See ImageFileImpl::construct2() for second phase. + // First phase of construction, can't do much until have the ImageFile object. See + // ImageFileImpl::construct2() for second phase. } void ImageFileImpl::construct2( const ustring &fileName, const ustring &mode ) { - /// Second phase of construction, now we have a well-formed ImageFile object. + // Second phase of construction, now we have a well-formed ImageFile object. -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "ImageFileImpl() called, fileName=" << fileName << " mode=" << mode << std::endl; #endif unusedLogicalStart_ = sizeof( E57FileHeader ); fileName_ = fileName; - /// Get shared_ptr to this object + // Get shared_ptr to this object ImageFileImplSharedPtr imf = shared_from_this(); // Accept "w" or "r" modes @@ -101,7 +101,7 @@ namespace e57 if ( !isWriter_ && ( mode != "r" ) ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_API_ARGUMENT, "mode=" + ustring( mode ) ); + throw E57_EXCEPTION2( ErrorBadAPIArgument, "mode=" + ustring( mode ) ); } file_ = nullptr; @@ -111,8 +111,8 @@ namespace e57 { try { - /// Open file for writing, truncate if already exists. - file_ = new CheckedFile( fileName_, CheckedFile::WriteCreate, checksumPolicy ); + // Open file for writing, truncate if already exists. + file_ = new CheckedFile( fileName_, CheckedFile::Write, checksumPolicy ); std::shared_ptr root( new StructureNodeImpl( imf ) ); root_ = root; @@ -136,8 +136,8 @@ namespace e57 // Reading try { - /// Open file for reading. - file_ = new CheckedFile( fileName_, CheckedFile::ReadOnly, checksumPolicy ); + // Open file for reading. + file_ = new CheckedFile( fileName_, CheckedFile::Read, checksumPolicy ); std::shared_ptr root( new StructureNodeImpl( imf ) ); root_ = root; @@ -159,17 +159,17 @@ namespace e57 try { - /// Create parser state, attach its event handers to the SAX2 reader + // Create parser state, attach its event handers to the SAX2 reader E57XmlParser parser( imf ); parser.init(); - /// Create input source (XML section of E57 file turned into a stream). + // Create input source (XML section of E57 file turned into a stream). E57XmlFileInputSource xmlSection( file_, xmlLogicalOffset_, xmlLogicalLength_ ); unusedLogicalStart_ = sizeof( E57FileHeader ); - /// Do the parse, building up the node tree + // Do the parse, building up the node tree parser.parse( xmlSection ); } catch ( ... ) @@ -183,15 +183,15 @@ namespace e57 void ImageFileImpl::construct2( const char *input, const uint64_t size ) { - /// Second phase of construction, now we have a well-formed ImageFile object. + // Second phase of construction, now we have a well-formed ImageFile object. -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "ImageFileImpl() called, fileName= mode=r" << std::endl; #endif unusedLogicalStart_ = sizeof( E57FileHeader ); fileName_ = ""; - /// Get shared_ptr to this object + // Get shared_ptr to this object ImageFileImplSharedPtr imf = shared_from_this(); isWriter_ = false; @@ -199,7 +199,7 @@ namespace e57 try { - /// Open file for reading. + // Open file for reading. file_ = new CheckedFile( input, size, checksumPolicy ); std::shared_ptr root( new StructureNodeImpl( imf ) ); @@ -222,17 +222,17 @@ namespace e57 try { - /// Create parser state, attach its event handers to the SAX2 reader + // Create parser state, attach its event handers to the SAX2 reader E57XmlParser parser( imf ); parser.init(); - /// Create input source (XML section of E57 file turned into a stream). + // Create input source (XML section of E57 file turned into a stream). E57XmlFileInputSource xmlSection( file_, xmlLogicalOffset_, xmlLogicalLength_ ); unusedLogicalStart_ = sizeof( E57FileHeader ); - /// Do the parse, building up the node tree + // Do the parse, building up the node tree parser.parse( xmlSection ); } catch ( ... ) @@ -244,42 +244,6 @@ namespace e57 } } - void ImageFileImpl::incrWriterCount() - { - writerCount_++; - } - - void ImageFileImpl::decrWriterCount() - { - writerCount_--; -#ifdef E57_MAX_DEBUG - if ( writerCount_ < 0 ) - { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "fileName=" + fileName_ + - " writerCount=" + toString( writerCount_ ) + - " readerCount=" + toString( readerCount_ ) ); - } -#endif - } - - void ImageFileImpl::incrReaderCount() - { - readerCount_++; - } - - void ImageFileImpl::decrReaderCount() - { - readerCount_--; -#ifdef E57_MAX_DEBUG - if ( readerCount_ < 0 ) - { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "fileName=" + fileName_ + - " writerCount=" + toString( writerCount_ ) + - " readerCount=" + toString( readerCount_ ) ); - } -#endif - } - std::shared_ptr ImageFileImpl::root() { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); @@ -289,38 +253,33 @@ namespace e57 void ImageFileImpl::close() { - /// If file already closed, have nothing to do - if ( !file_ ) + // If file already closed, have nothing to do + if ( file_ == nullptr ) { return; } if ( isWriter_ ) { - /// Go to end of file, note physical position + // Go to end of file, note physical position xmlLogicalOffset_ = unusedLogicalStart_; file_->seek( xmlLogicalOffset_, CheckedFile::Logical ); uint64_t xmlPhysicalOffset = file_->position( CheckedFile::Physical ); *file_ << "\n"; -#ifdef E57_OXYGEN_SUPPORT /*//??? \ - //??? *file_ << "\n";*/ -#endif //??? need to add name space attributes to e57Root root_->writeXml( shared_from_this(), *file_, 0, "e57Root" ); - /// Pad XML section so length is multiple of 4 + // Pad XML section so length is multiple of 4 while ( ( file_->position( CheckedFile::Logical ) - xmlLogicalOffset_ ) % 4 != 0 ) { *file_ << " "; } - /// Note logical length + // Note logical length xmlLogicalLength_ = file_->position( CheckedFile::Logical ) - xmlLogicalOffset_; - /// Init header contents + // Init header contents E57FileHeader header; memcpy( &header.fileSignature, "ASTM-E57", 8 ); @@ -331,11 +290,11 @@ namespace e57 header.xmlPhysicalOffset = xmlPhysicalOffset; header.xmlLogicalLength = xmlLogicalLength_; header.pageSize = CheckedFile::physicalPageSize; -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE header.dump(); #endif - /// Write header at beginning of file + // Write header at beginning of file file_->seek( 0 ); file_->write( reinterpret_cast( &header ), sizeof( header ) ); @@ -348,14 +307,14 @@ namespace e57 void ImageFileImpl::cancel() { - /// If file already closed, have nothing to do - if ( !file_ ) + // If file already closed, have nothing to do + if ( file_ == nullptr ) { return; } - /// Close the file and ulink (delete) it. - /// It is legal to cancel a read file, but file isn't deleted. + // Close the file and ulink (delete) it. + // It is legal to cancel a read file, but file isn't deleted. if ( isWriter_ ) { file_->unlink(); @@ -391,9 +350,9 @@ namespace e57 ImageFileImpl::~ImageFileImpl() { - /// Try to cancel if not already closed, but don't allow any exceptions to - /// propagate to caller (because in dtor). If writing, this will unlink the - /// file, so make sure call ImageFileImpl::close explicitly before dtor runs. + // Try to cancel if not already closed, but don't allow any exceptions to propagate to caller + // (because in dtor). If writing, this will unlink the file, so make sure call + // ImageFileImpl::close explicitly before dtor runs. try { cancel(); @@ -402,7 +361,7 @@ namespace e57 { }; - /// Just in case cancel failed without freeing file_, do free here. + // Just in case cancel failed without freeing file_, do free here. delete file_; file_ = nullptr; } @@ -411,11 +370,11 @@ namespace e57 { uint64_t oldLogicalStart = unusedLogicalStart_; - /// Reserve space at end of file + // Reserve space at end of file unusedLogicalStart_ += byteCount; - /// If caller won't write to file immediately, it should request that the - /// file be extended with zeros here + // If caller won't write to file immediately, it should request that the file be extended with + // zeros here. if ( doExtendNow ) { file_->extend( unusedLogicalStart_ ); @@ -441,21 +400,21 @@ namespace e57 //??? check if prefix characters ok, check if uri has a double quote char //(others?) - /// Check to make sure that neither prefix or uri is already defined. + // Check to make sure that neither prefix or uri is already defined. ustring dummy; if ( extensionsLookupPrefix( prefix, dummy ) ) { - throw E57_EXCEPTION2( E57_ERROR_DUPLICATE_NAMESPACE_PREFIX, "prefix=" + prefix + " uri=" + uri ); + throw E57_EXCEPTION2( ErrorDuplicateNamespacePrefix, "prefix=" + prefix + " uri=" + uri ); } if ( extensionsLookupUri( uri, dummy ) ) { - throw E57_EXCEPTION2( E57_ERROR_DUPLICATE_NAMESPACE_URI, "prefix=" + prefix + " uri=" + uri ); + throw E57_EXCEPTION2( ErrorDuplicateNamespaceURI, "prefix=" + prefix + " uri=" + uri ); ; } - /// Append at end of list + // Append at end of list nameSpaces_.emplace_back( prefix, uri ); } @@ -463,7 +422,7 @@ namespace e57 { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - /// Linear search for matching prefix + // Linear search for matching prefix std::vector::const_iterator it; for ( it = nameSpaces_.begin(); it < nameSpaces_.end(); ++it ) @@ -482,7 +441,7 @@ namespace e57 { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - /// Linear search for matching URI + // Linear search for matching URI std::vector::const_iterator it; for ( it = nameSpaces_.begin(); it < nameSpaces_.end(); ++it ) @@ -520,9 +479,9 @@ namespace e57 bool ImageFileImpl::isElementNameExtended( const ustring &elementName ) { - /// don't checkImageFileOpen + // don't checkImageFileOpen - /// Make sure doesn't have any "/" in it + // Make sure doesn't have any "/" in it size_t found = elementName.find_first_of( '/' ); if ( found != std::string::npos ) @@ -530,11 +489,12 @@ namespace e57 return false; } - ustring prefix, localPart; + ustring prefix; + ustring localPart; try { - /// Throws if elementName bad + // Throws if elementName bad elementNameParse( elementName, prefix, localPart ); } catch ( E57Exception & /*ex*/ ) @@ -542,13 +502,13 @@ namespace e57 return false; } - /// If get here, the name was good, so test if found a prefix part + // If get here, the name was good, so test if found a prefix part return ( prefix.length() > 0 ); } bool ImageFileImpl::isElementNameLegal( const ustring &elementName, bool allowNumber ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE // cout << "isElementNameLegal elementName=""" << elementName << """" << // std::endl; #endif @@ -556,7 +516,7 @@ namespace e57 { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - /// Throws if elementName bad + // Throws if elementName bad checkElementNameLegal( elementName, allowNumber ); } catch ( E57Exception & /*ex*/ ) @@ -564,20 +524,20 @@ namespace e57 return false; } - /// If get here, the name was good + // If get here, the name was good return true; } bool ImageFileImpl::isPathNameLegal( const ustring &pathName ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE // cout << "isPathNameLegal elementName=""" << pathName << """" << std::endl; #endif try { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - /// Throws if pathName bad + // Throws if pathName bad pathNameCheckWellFormed( pathName ); } catch ( E57Exception & /*ex*/ ) @@ -585,127 +545,45 @@ namespace e57 return false; } - /// If get here, the name was good + // If get here, the name was good return true; } void ImageFileImpl::checkElementNameLegal( const ustring &elementName, bool allowNumber ) { - /// no checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__) + // no checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__) ustring prefix; ustring localPart; - /// Throws if bad elementName + // Throws if bad elementName elementNameParse( elementName, prefix, localPart, allowNumber ); - /// If has prefix, it must be registered + // If has prefix, it must be registered ustring uri; if ( prefix.length() > 0 && !extensionsLookupPrefix( prefix, uri ) ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_PATH_NAME, "elementName=" + elementName + " prefix=" + prefix ); - } - } - - void ImageFileImpl::elementNameParse( const ustring &elementName, ustring &prefix, ustring &localPart, - bool allowNumber ) - { - /// no checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__) - - //??? check if elementName is good UTF-8? - - size_t len = elementName.length(); - - /// Empty name is bad - if ( len == 0 ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_PATH_NAME, "elementName=" + elementName ); - } - - unsigned char c = elementName[0]; - - /// If allowing numeric element name, check if first char is digit - if ( allowNumber && '0' <= c && c <= '9' ) - { - /// All remaining characters must be digits - for ( size_t i = 1; i < len; i++ ) - { - c = elementName[i]; - - if ( !( '0' <= c && c <= '9' ) ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_PATH_NAME, "elementName=" + elementName ); - } - } - - return; - } - - /// If first char is ASCII (< 128), check for legality - /// Don't test any part of a multi-byte code point sequence (c >= 128). - /// Don't allow ':' as first char. - if ( c < 128 && !( ( 'a' <= c && c <= 'z' ) || ( 'A' <= c && c <= 'Z' ) || c == '_' ) ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_PATH_NAME, "elementName=" + elementName ); - } - - /// If each following char is ASCII (<128), check for legality - /// Don't test any part of a multi-byte code point sequence (c >= 128). - for ( size_t i = 1; i < len; i++ ) - { - c = elementName[i]; - - if ( c < 128 && !( ( 'a' <= c && c <= 'z' ) || ( 'A' <= c && c <= 'Z' ) || c == '_' || c == ':' || - ( '0' <= c && c <= '9' ) || c == '-' || c == '.' ) ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_PATH_NAME, "elementName=" + elementName ); - } - } - - /// Check if has at least one colon, try to split it into prefix & localPart - size_t found = elementName.find_first_of( ':' ); - - if ( found != std::string::npos ) - { - /// Check doesn't have two colons - if ( elementName.find_first_of( ':', found + 1 ) != std::string::npos ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_PATH_NAME, "elementName=" + elementName ); - } - - /// Split element name at the colon - /// ??? split before check first/subsequent char legal? - prefix = elementName.substr( 0, found ); - localPart = elementName.substr( found + 1 ); - - if ( prefix.length() == 0 || localPart.length() == 0 ) - { - throw E57_EXCEPTION2( E57_ERROR_BAD_PATH_NAME, - "elementName=" + elementName + " prefix=" + prefix + " localPart=" + localPart ); - } - } - else - { - prefix = ""; - localPart = elementName; + throw E57_EXCEPTION2( ErrorBadPathName, + "elementName=" + elementName + " prefix=" + prefix ); } } void ImageFileImpl::pathNameCheckWellFormed( const ustring &pathName ) { - /// no checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__) + // no checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__) - /// Just call pathNameParse() which throws if not well formed + // Just call pathNameParse() which throws if not well formed bool isRelative = false; StringList fields; pathNameParse( pathName, isRelative, fields ); } - void ImageFileImpl::pathNameParse( const ustring &pathName, bool &isRelative, StringList &fields ) + void ImageFileImpl::pathNameParse( const ustring &pathName, bool &isRelative, + StringList &fields ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "pathNameParse pathname=" "" << pathName @@ -713,14 +591,14 @@ namespace e57 "" << std::endl; #endif - /// no checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__) + // no checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__) - /// Clear previous contents of fields vector + // Clear previous contents of fields vector fields.clear(); size_t start = 0; - /// Check if absolute path + // Check if absolute path if ( pathName[start] == '/' ) { isRelative = false; @@ -731,21 +609,24 @@ namespace e57 isRelative = true; } - /// Save strings in between each forward slash '/' - /// Don't ignore whitespace + // Save strings in between each forward slash '/' + // Don't ignore whitespace while ( start < pathName.size() ) { size_t slash = pathName.find_first_of( '/', start ); - /// Get element name from in between '/', check valid + // Get element name from in between '/', check valid ustring elementName = pathName.substr( start, slash - start ); if ( !isElementNameLegal( elementName ) ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_PATH_NAME, "pathName=" + pathName + " elementName=" + elementName ); + throw E57_EXCEPTION2( ErrorBadPathName, std::string( "pathName=" ) + .append( pathName ) + .append( " elementName=" ) + .append( elementName ) ); } - /// Add to list + // Add to list fields.push_back( elementName ); if ( slash == std::string::npos ) @@ -753,147 +634,184 @@ namespace e57 break; } - /// Handle case when pathname ends in /, e.g. "/foo/", add empty field at - /// end of list + // Handle case when pathname ends in /, e.g. "/foo/", add empty field at end of list if ( slash == pathName.size() - 1 ) { fields.emplace_back( "" ); break; } - /// Skip over the slash and keep going + // Skip over the slash and keep going start = slash + 1; } - /// Empty relative path is not allowed + // Empty relative path is not allowed if ( isRelative && fields.empty() ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_PATH_NAME, "pathName=" + pathName ); + throw E57_EXCEPTION2( ErrorBadPathName, "pathName=" + pathName ); } -#ifdef E57_MAX_VERBOSE - std::cout << "pathNameParse returning: isRelative=" << isRelative << " fields.size()=" << fields.size() - << " fields="; - for ( size_t i = 0; i < fields.size(); i++ ) +#ifdef E57_VERBOSE + std::cout << "pathNameParse returning: isRelative=" << isRelative + << " fields.size()=" << fields.size() << " fields="; + for ( auto &field : fields ) { - std::cout << fields[i] << ","; + std::cout << field << ","; } std::cout << std::endl; #endif } - ustring ImageFileImpl::pathNameUnparse( bool isRelative, const std::vector &fields ) + void ImageFileImpl::incrWriterCount() { - ustring path; + writerCount_++; + } - if ( !isRelative ) + void ImageFileImpl::decrWriterCount() + { + writerCount_--; + +#if ( E57_VALIDATION_LEVEL == VALIDATION_DEEP ) + if ( writerCount_ < 0 ) { - path.push_back( '/' ); + throw E57_EXCEPTION2( ErrorInternal, "fileName=" + fileName_ + + " writerCount=" + toString( writerCount_ ) + + " readerCount=" + toString( readerCount_ ) ); } +#endif + } - for ( unsigned i = 0; i < fields.size(); ++i ) - { - path.append( fields.at( i ) ); + void ImageFileImpl::incrReaderCount() + { + readerCount_++; + } - if ( i < fields.size() - 1 ) - { - path.push_back( '/' ); - } - } + void ImageFileImpl::decrReaderCount() + { + readerCount_--; - return path; +#if ( E57_VALIDATION_LEVEL == VALIDATION_DEEP ) + if ( readerCount_ < 0 ) + { + throw E57_EXCEPTION2( ErrorInternal, "fileName=" + fileName_ + + " writerCount=" + toString( writerCount_ ) + + " readerCount=" + toString( readerCount_ ) ); + } +#endif } - void ImageFileImpl::readFileHeader( CheckedFile *file, E57FileHeader &header ) + void ImageFileImpl::elementNameParse( const ustring &elementName, ustring &prefix, + ustring &localPart, bool allowNumber ) { - /// Double check that compiler thinks sizeof header is what it is supposed to - /// be - static_assert( sizeof( E57FileHeader ) == 48, "Unexpected size of E57FileHeader" ); + // no checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__) - /// Fetch the file header - file->read( reinterpret_cast( &header ), sizeof( header ) ); + //??? check if elementName is good UTF-8? -#ifdef E57_MAX_VERBOSE - header.dump(); -#endif + size_t len = elementName.length(); - /// Check signature - if ( strncmp( header.fileSignature, "ASTM-E57", 8 ) != 0 ) + // Empty name is bad + if ( len == 0 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_FILE_SIGNATURE, "fileName=" + file->fileName() ); + throw E57_EXCEPTION2( ErrorBadPathName, "elementName=" + elementName ); } - /// Check file version compatibility - if ( header.majorVersion > E57_FORMAT_MAJOR ) + unsigned char c = elementName[0]; + + // If allowing numeric element name, check if first char is digit + if ( allowNumber && '0' <= c && c <= '9' ) { - throw E57_EXCEPTION2( E57_ERROR_UNKNOWN_FILE_VERSION, - "fileName=" + file->fileName() + - " header.majorVersion=" + toString( header.majorVersion ) + - " header.minorVersion=" + toString( header.minorVersion ) ); + // All remaining characters must be digits + for ( size_t i = 1; i < len; i++ ) + { + c = elementName[i]; + + if ( c < '0' || c > '9' ) + { + throw E57_EXCEPTION2( ErrorBadPathName, "elementName=" + elementName ); + } + } + + return; } - /// If is a prototype version (majorVersion==0), then minorVersion has to - /// match too. In production versions (majorVersion==E57_FORMAT_MAJOR), - /// should be able to handle any minor version. - if ( header.majorVersion == E57_FORMAT_MAJOR && header.minorVersion > E57_FORMAT_MINOR ) + // If first char is ASCII (< 128), check for legality + // Don't test any part of a multi-byte code point sequence (c >= 128). + // Don't allow ':' as first char. + if ( c < 128 && !( ( 'a' <= c && c <= 'z' ) || ( 'A' <= c && c <= 'Z' ) || c == '_' ) ) { - throw E57_EXCEPTION2( E57_ERROR_UNKNOWN_FILE_VERSION, - "fileName=" + file->fileName() + - " header.majorVersion=" + toString( header.majorVersion ) + - " header.minorVersion=" + toString( header.minorVersion ) ); + throw E57_EXCEPTION2( ErrorBadPathName, "elementName=" + elementName ); } - /// Check if file length matches actual physical length - if ( header.filePhysicalLength != file->length( CheckedFile::Physical ) ) + // If each following char is ASCII (<128), check for legality + // Don't test any part of a multi-byte code point sequence (c >= 128). + for ( size_t i = 1; i < len; i++ ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_FILE_LENGTH, - "fileName=" + file->fileName() + - " header.filePhysicalLength=" + toString( header.filePhysicalLength ) + - " file->length=" + toString( file->length( CheckedFile::Physical ) ) ); + c = elementName[i]; + + if ( c < 128 && !( ( 'a' <= c && c <= 'z' ) || ( 'A' <= c && c <= 'Z' ) || c == '_' || + c == ':' || ( '0' <= c && c <= '9' ) || c == '-' || c == '.' ) ) + { + throw E57_EXCEPTION2( ErrorBadPathName, "elementName=" + elementName ); + } } - /// Check that page size is correct constant - if ( header.majorVersion != 0 && header.pageSize != CheckedFile::physicalPageSize ) + // Check if has at least one colon, try to split it into prefix & localPart + size_t found = elementName.find_first_of( ':' ); + + if ( found != std::string::npos ) + { + // Check doesn't have two colons + if ( elementName.find_first_of( ':', found + 1 ) != std::string::npos ) + { + throw E57_EXCEPTION2( ErrorBadPathName, "elementName=" + elementName ); + } + + // Split element name at the colon + // ??? split before check first/subsequent char legal? + prefix = elementName.substr( 0, found ); + localPart = elementName.substr( found + 1 ); + + if ( prefix.length() == 0 || localPart.length() == 0 ) + { + throw E57_EXCEPTION2( ErrorBadPathName, "elementName=" + elementName + " prefix=" + + prefix + " localPart=" + localPart ); + } + } + else { - throw E57_EXCEPTION2( E57_ERROR_BAD_FILE_LENGTH, "fileName=" + file->fileName() ); + prefix = ""; + localPart = elementName; } } - void ImageFileImpl::checkImageFileOpen( const char *srcFileName, int srcLineNumber, - const char *srcFunctionName ) const + ustring ImageFileImpl::pathNameUnparse( bool isRelative, const std::vector &fields ) { - if ( !isOpen() ) + ustring path; + + if ( !isRelative ) { - throw E57Exception( E57_ERROR_IMAGEFILE_NOT_OPEN, "fileName=" + fileName(), srcFileName, srcLineNumber, - srcFunctionName ); + path.push_back( '/' ); } - } -#ifdef E57_DEBUG - void ImageFileImpl::dump( int indent, std::ostream &os ) const - { - /// no checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__) - os << space( indent ) << "fileName: " << fileName_ << std::endl; - os << space( indent ) << "writerCount: " << writerCount_ << std::endl; - os << space( indent ) << "readerCount: " << readerCount_ << std::endl; - os << space( indent ) << "isWriter: " << isWriter_ << std::endl; - for ( size_t i = 0; i < extensionsCount(); i++ ) + for ( unsigned i = 0; i < fields.size(); ++i ) { - os << space( indent ) << "nameSpace[" << i << "]: prefix=" << extensionsPrefix( i ) - << " uri=" << extensionsUri( i ) << std::endl; + path.append( fields.at( i ) ); + + if ( i < fields.size() - 1 ) + { + path.push_back( '/' ); + } } - os << space( indent ) << "root: " << std::endl; - root_->dump( indent + 2, os ); + + return path; } -#endif unsigned ImageFileImpl::bitsNeeded( int64_t minimum, int64_t maximum ) { - /// Relatively quick way to compute ceil(log2(maximum - minimum + 1))); - /// Uses only integer operations and is machine independent (no assembly - /// code). Find the bit position of the first 1 (from left) in the binary - /// form of stateCountMinus1. - ///??? move to E57Utility? + // Relatively quick way to compute ceil(log2(maximum - minimum + 1))); + // Uses only integer operations and is machine independent (no assembly code). Find the bit + // position of the first 1 (from left) in the binary form of stateCountMinus1. + //??? move to E57Utility? uint64_t stateCountMinus1 = maximum - minimum; @@ -942,4 +860,86 @@ namespace e57 return log2; } + +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT + void ImageFileImpl::dump( int indent, std::ostream &os ) const + { + // no checkImageFileOpen(__FILE__, __LINE__, __FUNCTION__) + os << space( indent ) << "fileName: " << fileName_ << std::endl; + os << space( indent ) << "writerCount: " << writerCount_ << std::endl; + os << space( indent ) << "readerCount: " << readerCount_ << std::endl; + os << space( indent ) << "isWriter: " << isWriter_ << std::endl; + for ( size_t i = 0; i < extensionsCount(); i++ ) + { + os << space( indent ) << "nameSpace[" << i << "]: prefix=" << extensionsPrefix( i ) + << " uri=" << extensionsUri( i ) << std::endl; + } + os << space( indent ) << "root: " << std::endl; + root_->dump( indent + 2, os ); + } +#endif + + void ImageFileImpl::readFileHeader( CheckedFile *file, E57FileHeader &header ) + { + // Double check that compiler thinks sizeof header is what it is supposed to be + static_assert( sizeof( E57FileHeader ) == 48, "Unexpected size of E57FileHeader" ); + + // Fetch the file header + file->read( reinterpret_cast( &header ), sizeof( header ) ); + +#ifdef E57_VERBOSE + header.dump(); +#endif + + // Check signature + if ( strncmp( header.fileSignature, "ASTM-E57", 8 ) != 0 ) + { + throw E57_EXCEPTION2( ErrorBadFileSignature, "fileName=" + file->fileName() ); + } + + // Check file version compatibility + if ( header.majorVersion > E57_FORMAT_MAJOR ) + { + throw E57_EXCEPTION2( ErrorUnknownFileVersion, + "fileName=" + file->fileName() + + " header.majorVersion=" + toString( header.majorVersion ) + + " header.minorVersion=" + toString( header.minorVersion ) ); + } + + // If is a prototype version (majorVersion==0), then minorVersion has to match too. In + // production versions (majorVersion==E57_FORMAT_MAJOR), should be able to handle any minor + // version. + if ( header.majorVersion == E57_FORMAT_MAJOR && header.minorVersion > E57_FORMAT_MINOR ) + { + throw E57_EXCEPTION2( ErrorUnknownFileVersion, + "fileName=" + file->fileName() + + " header.majorVersion=" + toString( header.majorVersion ) + + " header.minorVersion=" + toString( header.minorVersion ) ); + } + + // Check if file length matches actual physical length + if ( header.filePhysicalLength != file->length( CheckedFile::Physical ) ) + { + throw E57_EXCEPTION2( ErrorBadFileLength, + "fileName=" + file->fileName() + " header.filePhysicalLength=" + + toString( header.filePhysicalLength ) + " file->length=" + + toString( file->length( CheckedFile::Physical ) ) ); + } + + // Check that page size is correct constant + if ( header.majorVersion != 0 && header.pageSize != CheckedFile::physicalPageSize ) + { + throw E57_EXCEPTION2( ErrorBadFileLength, "fileName=" + file->fileName() ); + } + } + + void ImageFileImpl::checkImageFileOpen( const char *srcFileName, int srcLineNumber, + const char *srcFunctionName ) const + { + if ( !isOpen() ) + { + throw E57Exception( ErrorImageFileNotOpen, "fileName=" + fileName(), srcFileName, + srcLineNumber, srcFunctionName ); + } + } } diff --git a/src/3rdParty/libE57Format/src/ImageFileImpl.h b/src/3rdParty/libE57Format/src/ImageFileImpl.h index 6085960944435..c107969b4d59d 100644 --- a/src/3rdParty/libE57Format/src/ImageFileImpl.h +++ b/src/3rdParty/libE57Format/src/ImageFileImpl.h @@ -41,10 +41,13 @@ namespace e57 class ImageFileImpl : public std::enable_shared_from_this { public: - ImageFileImpl( ReadChecksumPolicy policy ); + explicit ImageFileImpl( ReadChecksumPolicy policy ); + void construct2( const ustring &fileName, const ustring &mode ); - void construct2( const char *input, const uint64_t size ); + void construct2( const char *input, uint64_t size ); + std::shared_ptr root(); + void close(); void cancel(); bool isOpen() const; @@ -62,28 +65,31 @@ namespace e57 bool extensionsLookupPrefix( const ustring &prefix, ustring &uri ) const; bool extensionsLookupUri( const ustring &uri, ustring &prefix ) const; size_t extensionsCount() const; - ustring extensionsPrefix( const size_t index ) const; - ustring extensionsUri( const size_t index ) const; + ustring extensionsPrefix( size_t index ) const; + ustring extensionsUri( size_t index ) const; /// Utility functions: bool isElementNameExtended( const ustring &elementName ); bool isElementNameLegal( const ustring &elementName, bool allowNumber = true ); bool isPathNameLegal( const ustring &pathName ); void checkElementNameLegal( const ustring &elementName, bool allowNumber = true ); - void elementNameParse( const ustring &elementName, ustring &prefix, ustring &localPart, bool allowNumber = true ); void pathNameCheckWellFormed( const ustring &pathName ); void pathNameParse( const ustring &pathName, bool &isRelative, StringList &fields ); - ustring pathNameUnparse( bool isRelative, const StringList &fields ); - unsigned bitsNeeded( int64_t minimum, int64_t maximum ); void incrWriterCount(); void decrWriterCount(); void incrReaderCount(); void decrReaderCount(); - /// Diagnostic functions: -#ifdef E57_DEBUG + static void elementNameParse( const ustring &elementName, ustring &prefix, ustring &localPart, + bool allowNumber = true ); + + static ustring pathNameUnparse( bool isRelative, const StringList &fields ); + + static unsigned bitsNeeded( int64_t minimum, int64_t maximum ); + +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const; #endif @@ -91,13 +97,12 @@ namespace e57 friend class E57XmlParser; friend class BlobNodeImpl; friend class CompressedVectorWriterImpl; - friend class CompressedVectorReaderImpl; //??? add file() instead of - // accessing file_, others - // friends too + friend class CompressedVectorReaderImpl; static void readFileHeader( CheckedFile *file, E57FileHeader &header ); - void checkImageFileOpen( const char *srcFileName, int srcLineNumber, const char *srcFunctionName ) const; + void checkImageFileOpen( const char *srcFileName, int srcLineNumber, + const char *srcFunctionName ) const; ustring fileName_; bool isWriter_; @@ -108,11 +113,11 @@ namespace e57 CheckedFile *file_; - /// Read file attributes + // Read file attributes uint64_t xmlLogicalOffset_; uint64_t xmlLogicalLength_; - /// Write file attributes + // Write file attributes uint64_t unusedLogicalStart_; /// Bidirectional map from namespace prefix to uri diff --git a/src/3rdParty/libE57Format/src/IntegerNode.cpp b/src/3rdParty/libE57Format/src/IntegerNode.cpp new file mode 100644 index 0000000000000..293e46cc88893 --- /dev/null +++ b/src/3rdParty/libE57Format/src/IntegerNode.cpp @@ -0,0 +1,324 @@ +/* + * IntegerNode.cpp - implementation of public functions of the IntegerNode class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file IntegerNode.cpp + +#include "IntegerNodeImpl.h" +#include "StringFunctions.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/*! +@brief Check whether IntegerNode class invariant is true + +@param [in] doRecurse If true, also check invariants of all children or sub-objects recursively. +@param [in] doUpcast If true, also check invariants of the generic Node class. + +@details +This function checks at least the assertions in the documented class invariant description (see +class reference page for this object). Other internal invariants that are implementation-dependent +may also be checked. If any invariant clause is violated, an ::ErrorInvarianceViolation E57Exception +is thrown. + +Checking the invariant recursively may be expensive if the tree is large, so should be used +judiciously, in debug versions of the application. + +@post No visible state is modified. + +@throw ::ErrorInvarianceViolation or any other E57 ErrorCode +*/ +void IntegerNode::checkInvariant( bool doRecurse, bool doUpcast ) const +{ + UNUSED( doRecurse ); + + // If destImageFile not open, can't test invariant (almost every call would throw) + if ( !destImageFile().isOpen() ) + { + return; + } + + // If requested, call Node::checkInvariant + if ( doUpcast ) + { + static_cast( *this ).checkInvariant( false, false ); + } + + if ( value() < minimum() || value() > maximum() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } +} + +/*! +@class e57::IntegerNode + +@brief An E57 element encoding an integer value. + +@details +An IntegerNode is a terminal node (i.e. having no children) that holds an integer value, and +minimum/maximum bounds. Once the IntegerNode value and attributes are set at creation, they may not +be modified. + +The minimum attribute may be a number in the interval [-2^63, 2^63). +The maximum attribute may be a number in the interval [minimum, 2^63). +The value may be a number in the interval [minimum, maximum]. + +See Node class discussion for discussion of the common functions that StructureNode supports. + +@section IntegerNode_invariant Class Invariant +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude IntegerNode.cpp +@skip void IntegerNode::checkInvariant +@until ^} + +@see Node, CompressedVector +*/ + +/*! +@brief Create an E57 element for storing a integer value. + +@param [in] destImageFile The ImageFile where the new node will eventually be stored. +@param [in] value The integer value of the element. +@param [in] minimum The smallest value that the element may take. +@param [in] maximum The largest value that the element may take. + +@details +An IntegerNode stores an integer value, and a lower and upper bound. +The IntegerNode class corresponds to the ASTM E57 standard Integer element. +See the class discussion at bottom of IntegerNode page for more details. + +The @a destImageFile indicates which ImageFile the IntegerNode will eventually be attached to. A +node is attached to an ImageFile by adding it underneath the predefined root of the ImageFile +(gotten from ImageFile::root). It is not an error to fail to attach the IntegerNode to the @a +destImageFile. It is an error to attempt to attach the IntegerNode to a different ImageFile. + +@warning It is an error to give an @a value outside the @a minimum / @a maximum bounds, even if the +IntegerNode is destined to be used in a CompressedVectorNode prototype (where the @a value will be +ignored). If the IntegerNode is to be used in a prototype, it is recommended to specify a @a value = +0 if 0 is within bounds, or a @a value = @a minimum if 0 is not within bounds. + +@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be true). +@pre The @a destImageFile must have been opened in write mode (i.e. destImageFile.isWritable() must +be true). +@pre minimum <= value <= maximum + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorFileReadOnly +@throw ::ErrorValueOutOfBounds +@throw ::ErrorInternal All objects in undocumented state + +@see IntegerNode::value, Node, CompressedVectorNode, CompressedVectorNode::prototype +*/ +IntegerNode::IntegerNode( const ImageFile &destImageFile, int64_t value, int64_t minimum, + int64_t maximum ) : + impl_( new IntegerNodeImpl( destImageFile.impl(), value, minimum, maximum ) ) +{ +} + +/*! +@brief Is this a root node. +@copydetails Node::isRoot() +*/ +bool IntegerNode::isRoot() const +{ + return impl_->isRoot(); +} + +/*! +@brief Return parent of node, or self if a root node. +@copydetails Node::parent() +*/ +Node IntegerNode::parent() const +{ + return Node( impl_->parent() ); +} + +/*! +@brief Get absolute pathname of node. +@copydetails Node::pathName() +*/ +ustring IntegerNode::pathName() const +{ + return impl_->pathName(); +} + +/*! +@brief Get elementName string, that identifies the node in its parent. +@copydetails Node::elementName() +*/ +ustring IntegerNode::elementName() const +{ + return impl_->elementName(); +} + +/*! +@brief Get the ImageFile that was declared as the destination for the node when it was created. +@copydetails Node::destImageFile() +*/ +ImageFile IntegerNode::destImageFile() const +{ + return ImageFile( impl_->destImageFile() ); +} + +/*! +@brief Has node been attached into the tree of an ImageFile. +@copydetails Node::isAttached() +*/ +bool IntegerNode::isAttached() const +{ + return impl_->isAttached(); +} + +/*! +@brief Get integer value stored. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return integer value stored. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see IntegerNode::minimum, IntegerNode::maximum +*/ +int64_t IntegerNode::value() const +{ + return impl_->value(); +} + +/*! +@brief Get the declared minimum that the value may take. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The declared minimum that the value may take. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see IntegerNode::value +*/ +int64_t IntegerNode::minimum() const +{ + return impl_->minimum(); +} + +/*! +@brief Get the declared maximum that the value may take. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The declared maximum that the value may take. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see IntegerNode::value +*/ +int64_t IntegerNode::maximum() const +{ + return impl_->maximum(); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void IntegerNode::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void IntegerNode::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif + +/*! +@brief Upcast a IntegerNode handle to a generic Node handle. + +@details +An upcast is always safe, and the compiler can automatically insert it for initializations of Node +variables and Node function arguments. + +@return A smart Node handle referencing the underlying object. + +@throw No E57Exceptions. + +@see explanation in Node, Node::type(), IntegerNode(const Node&) +*/ +IntegerNode::operator Node() const +{ + // Upcast from shared_ptr to SharedNodeImplPtr and construct a Node object + return Node( impl_ ); +} + +/*! +@brief Downcast a generic Node handle to a IntegerNode handle. + +@param [in] n The generic handle to downcast. + +@details +The handle @a n must be for an underlying IntegerNode, otherwise an exception is thrown. In designs +that need to avoid the exception, use Node::type() to determine the actual type of the @a n before +downcasting. This function must be explicitly called (c++ compiler cannot insert it automatically). + +@throw ::ErrorBadNodeDowncast + +@see Node::type(), IntegerNode::operator Node() +*/ +IntegerNode::IntegerNode( const Node &n ) +{ + if ( n.type() != TypeInteger ) + { + throw E57_EXCEPTION2( ErrorBadNodeDowncast, "nodeType=" + toString( n.type() ) ); + } + + // Set our shared_ptr to the downcast shared_ptr + impl_ = std::static_pointer_cast( n.impl() ); +} + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +IntegerNode::IntegerNode( std::shared_ptr ni ) : impl_( ni ) +{ +} +/// @endcond diff --git a/src/3rdParty/libE57Format/src/IntegerNodeImpl.cpp b/src/3rdParty/libE57Format/src/IntegerNodeImpl.cpp index 492baab0ae253..373042a3fee7c 100644 --- a/src/3rdParty/libE57Format/src/IntegerNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/IntegerNodeImpl.cpp @@ -27,22 +27,24 @@ #include "IntegerNodeImpl.h" #include "CheckedFile.h" +#include "StringFunctions.h" namespace e57 { - IntegerNodeImpl::IntegerNodeImpl( ImageFileImplWeakPtr destImageFile, int64_t value, int64_t minimum, - int64_t maximum ) : + IntegerNodeImpl::IntegerNodeImpl( ImageFileImplWeakPtr destImageFile, int64_t value, + int64_t minimum, int64_t maximum ) : NodeImpl( destImageFile ), value_( value ), minimum_( minimum ), maximum_( maximum ) { // don't checkImageFileOpen, NodeImpl() will do it - /// Enforce the given bounds + // Enforce the given bounds if ( value < minimum || maximum < value ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_OUT_OF_BOUNDS, - "this->pathName=" + this->pathName() + " value=" + toString( value ) + - " minimum=" + toString( minimum ) + " maximum=" + toString( maximum ) ); + throw E57_EXCEPTION2( ErrorValueOutOfBounds, "this->pathName=" + this->pathName() + + " value=" + toString( value ) + + " minimum=" + toString( minimum ) + + " maximum=" + toString( maximum ) ); } } @@ -50,30 +52,30 @@ namespace e57 { // don't checkImageFileOpen - /// Same node type? - if ( ni->type() != E57_INTEGER ) + // Same node type? + if ( ni->type() != TypeInteger ) { return ( false ); } - /// Downcast to shared_ptr + // Downcast to shared_ptr std::shared_ptr ii( std::static_pointer_cast( ni ) ); - /// minimum must match + // minimum must match if ( minimum_ != ii->minimum_ ) { return ( false ); } - /// maximum must match + // maximum must match if ( maximum_ != ii->maximum_ ) { return ( false ); } - /// ignore value_, doesn't have to match + // ignore value_, doesn't have to match - /// Types match + // Types match return ( true ); } @@ -81,7 +83,7 @@ namespace e57 { // don't checkImageFileOpen - /// We have no sub-structure, so if path not empty return false + // We have no sub-structure, so if path not empty return false return pathName.empty(); } @@ -107,10 +109,10 @@ namespace e57 { // don't checkImageFileOpen - /// We are a leaf node, so verify that we are listed in set. + // We are a leaf node, so verify that we are listed in set. if ( pathNames.find( relativePathName( origin ) ) == pathNames.end() ) { - throw E57_EXCEPTION2( E57_ERROR_NO_BUFFER_FOR_ELEMENT, "this->pathName=" + this->pathName() ); + throw E57_EXCEPTION2( ErrorNoBufferForElement, "this->pathName=" + this->pathName() ); } } @@ -120,7 +122,7 @@ namespace e57 // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName ) + if ( forcedFieldName != nullptr ) { fieldName = forcedFieldName; } @@ -131,17 +133,17 @@ namespace e57 cf << space( indent ) << "<" << fieldName << " type=\"Integer\""; - /// Don't need to write if are default values - if ( minimum_ != E57_INT64_MIN ) + // Don't need to write if are default values + if ( minimum_ != INT64_MIN ) { cf << " minimum=\"" << minimum_ << "\""; } - if ( maximum_ != E57_INT64_MAX ) + if ( maximum_ != INT64_MAX ) { cf << " maximum=\"" << maximum_ << "\""; } - /// Write value as child text, unless it is the default value + // Write value as child text, unless it is the default value if ( value_ != 0 ) { cf << ">" << value_ << "\n"; @@ -152,7 +154,7 @@ namespace e57 } } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void IntegerNodeImpl::dump( int indent, std::ostream &os ) const { // don't checkImageFileOpen diff --git a/src/3rdParty/libE57Format/src/IntegerNodeImpl.h b/src/3rdParty/libE57Format/src/IntegerNodeImpl.h index d30e748a047a6..faa42e3a68e3b 100644 --- a/src/3rdParty/libE57Format/src/IntegerNodeImpl.h +++ b/src/3rdParty/libE57Format/src/IntegerNodeImpl.h @@ -33,14 +33,15 @@ namespace e57 class IntegerNodeImpl : public NodeImpl { public: - IntegerNodeImpl( ImageFileImplWeakPtr destImageFile, int64_t value = 0, int64_t minimum = 0, - int64_t maximum = 0 ); + explicit IntegerNodeImpl( ImageFileImplWeakPtr destImageFile, int64_t value = 0, + int64_t minimum = 0, int64_t maximum = 0 ); ~IntegerNodeImpl() override = default; NodeType type() const override { - return E57_INTEGER; + return TypeInteger; } + bool isTypeEquivalent( NodeImplSharedPtr ni ) override; bool isDefined( const ustring &pathName ) override; @@ -53,7 +54,7 @@ namespace e57 void writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, const char *forcedFieldName = nullptr ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif diff --git a/src/3rdParty/libE57Format/src/Node.cpp b/src/3rdParty/libE57Format/src/Node.cpp new file mode 100644 index 0000000000000..1e2cb09e639c5 --- /dev/null +++ b/src/3rdParty/libE57Format/src/Node.cpp @@ -0,0 +1,604 @@ +/* + * Node.cpp - implementation of public functions of the Node class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file Node.cpp + +#include "NodeImpl.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/*! +@brief Check whether Node class invariant is true + +@param [in] doRecurse If true, also check invariants of all children or sub-objects recursively. +@param [in] doDowncast If true, also check any invariants of the actual derived type in addition to +the generic node invariants. + +@details +This function checks at least the assertions in the documented class invariant description (see +class reference page for this object). Other internal invariants that are implementation-dependent +may also be checked. If any invariant clause is violated, an E57Exception with errorCode of +ErrorInvarianceViolation is thrown. + +Specifying doRecurse=true only makes sense if doDowncast=true is also specified (the generic Node +has no way to access any children). Checking the invariant recursively may be expensive if the tree +is large, so should be used judiciously, in debug versions of the application. + +@post No visible state is modified. + +@throw ::ErrorInvarianceViolation or any other E57 ErrorCode + +@see Class Invariant section in Node, IntegerNode::checkInvariant, +ScaledIntegerNode::checkInvariant, FloatNode::checkInvariant, BlobNode::checkInvariant, +StructureNode::checkInvariant, VectorNode::checkInvariant, CompressedVectorNode::checkInvariant +*/ +void Node::checkInvariant( bool doRecurse, bool doDowncast ) +{ + ImageFile imf = destImageFile(); + + // If destImageFile not open, can't test invariant (almost every call would throw) + if ( !imf.isOpen() ) + { + return; + } + + // Parent attachment state is same as this attachment state + if ( isAttached() != parent().isAttached() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Parent destination ImageFile is same as this + if ( imf != parent().destImageFile() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // If this is the ImageFile root node + if ( *this == imf.root() ) + { + // Must be attached + if ( !isAttached() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Must be is a root node + if ( !isRoot() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + + // If this is a root node + if ( isRoot() ) + { + // Absolute pathName is "/" + if ( pathName() != "/" ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // parent() returns this node + if ( *this != parent() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + else + { + // Non-root can't be own parent + if ( *this == parent() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // pathName is concatenation of parent pathName and this elementName + if ( parent().isRoot() ) + { + if ( pathName() != "/" + elementName() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + else + { + if ( pathName() != parent().pathName() + "/" + elementName() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + + // Non-root nodes must be children of either a VectorNode or StructureNode + if ( parent().type() == TypeVector ) + { + VectorNode v = static_cast( parent() ); + + // Must be defined in parent VectorNode with this elementName + if ( !v.isDefined( elementName() ) ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Getting child of parent with this elementName must return this + if ( v.get( elementName() ) != *this ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + else if ( parent().type() == TypeStructure ) + { + StructureNode s = static_cast( parent() ); + + // Must be defined in parent VectorNode with this elementName + if ( !s.isDefined( elementName() ) ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Getting child of parent with this elementName must return this + if ( s.get( elementName() ) != *this ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + else + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + + // If this is attached + if ( isAttached() ) + { + // Get root of this + Node n = *this; + while ( !n.isRoot() ) + { + n = n.parent(); + } + + // If in tree of ImageFile (could be in a prototype instead) + if ( n == imf.root() ) + { + // pathName must be defined + if ( !imf.root().isDefined( pathName() ) ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Getting by absolute pathName must be this + if ( imf.root().get( pathName() ) != *this ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } + } + + // If requested, check invariants of derived types: + if ( doDowncast ) + { + switch ( type() ) + { + case TypeStructure: + { + StructureNode s( *this ); + s.checkInvariant( doRecurse, false ); + } + break; + case TypeVector: + { + VectorNode v( *this ); + v.checkInvariant( doRecurse, false ); + } + break; + case TypeCompressedVector: + { + CompressedVectorNode cv( *this ); + cv.checkInvariant( doRecurse, false ); + } + break; + case TypeInteger: + { + IntegerNode i( *this ); + i.checkInvariant( doRecurse, false ); + } + break; + case TypeScaledInteger: + { + ScaledIntegerNode si( *this ); + si.checkInvariant( doRecurse, false ); + } + break; + case TypeFloat: + { + FloatNode f( *this ); + f.checkInvariant( doRecurse, false ); + } + break; + case TypeString: + { + StringNode s( *this ); + s.checkInvariant( doRecurse, false ); + } + break; + case TypeBlob: + { + BlobNode b( *this ); + b.checkInvariant( doRecurse, false ); + } + break; + default: + break; + } + } +} + +/*! +@class e57::Node + +@brief Generic handle to any of the 8 types of E57 element objects. + +@details +A Node is a generic handle to an underlying object that is any of the eight type of E57 element +objects. Each of the eight node types support the all the functions of the Node class. A Node is a +vertex in a tree (acyclic graph), which is a hierarchical organization of nodes. At the top of the +hierarchy is a single root Node. If a Node is a container type (StructureNode, VectorNode, +CompressedVectorNode) it may have child nodes. The following are non-container type nodes (also +known as terminal nodes): IntegerNode, ScaledIntegerNode, FloatNode, StringNode, BlobNode. Terminal +nodes store various types of values and cannot have children. Each Node has an elementName, which is +a string that uniquely identifies it within the children of its parent. Children of a StructureNode +have elementNames that are explicitly given by the API user. Children of a VectorNode or +CompressedVectorNode have element names that are string reorientations of the Node's positional +index, starting at "0". A path name is a sequence elementNames (divided by "/") that must be +traversed to get from a Node to one of its descendents. + +Data is organized in an E57 format file (an ImageFile) hierarchically. Each ImageFile has a +predefined root node that other nodes can be attached to as children (either directly or +indirectly). A Node can exist temporarily without being attached to an ImageFile, however the state +will not be saved in the associated file, and the state will be lost if the program exits. + +A handle to a generic Node may be safely be converted to and from a handle to the Node's true +underlying type. Since an attempt to convert a generic Node to a incorrect handle type will fail +with an exception, the true type should be interrogated beforehand. + +Due to the set-once design of the Foundation API, terminal nodes are immutable (i.e. their values +and attributes can't change after creation). Once a parent-child relationship has been established, +it cannot be changed. + +Only generic operations are available for a Node, to access more specific operations (e.g. +StructureNode::childCount) the generic handle must be converted to the node type of the underlying +object. This conversion is done in a type-safe way using "downcasting" (see discussion below). + +@section node_Downcasting Downcasting +The conversion from a general handle type to a specific handle type is called "downcasting". Each of +the 8 specific node types have a downcast function (see IntegerNode::IntegerNode(const Node&) for +example). If a downcast is requested to an incorrect type (e.g. taking a Node handle that is +actually a FloatNode and trying to downcast it to a IntegerNode), an E57Exception is thrown with an +ErrorCode of ::ErrorBadNodeDowncast. Depending on the program design, throwing a bad downcast +exception might be acceptable, if an element must be a specific type and no recovery is possible. If +a standard requires an element be one several types, then Node::type() should be used to interrogate +the type in an @c if or @c switch statement. Downcasting is "dangerous" (can fail with an exception) +so the API requires the programmer to explicitly call the downcast functions rather than have the +c++ compiler insert them automatically. + +@section node_Upcasting Upcasting +The conversion of a specific node handle (e.g. IntegerNode) to a general Node handle is called +"upcasting". Each of the 8 specific node types have an upcast function (see IntegerNode::operator +Node() for example). Upcasting is "safe" (can't cause an exception) so the API allows the c++ +compiler to insert them automatically. Upcasting is useful if you have a specific node handle and +want to call a function that takes a generic Node handle argument. In this case, the function can be +called with the specific handle and the compiler will automatically insert the upcast conversion. +This implicit conversion allows one function, with an argument of type Node, to handle operations +that apply to all 8 types of nodes (e.g. StructureNode::set()). + +@section node_invariant Class Invariant +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude Node.cpp +@skip void Node::checkInvariant +@until ^} + +@see StructureNode, VectorNode, CompressedVectorNode, IntegerNode, ScaledIntegerNode, FloatNode, +StringNode, BlobNode +*/ + +/*! +@brief Return the NodeType of a generic Node. + +@details +This function allows the actual node type to be interrogated before upcasting the handle to the +actual node type (see Upcasting and Downcasting section in Node). + +@post No visible state is modified. + +@return The NodeType of a generic Node, which may be one of the following NodeType enumeration +values: +::TypeStructure, ::TypeVector, ::TypeCompressedVector, ::TypeInteger, ::TypeScaledInteger, +::TypeFloat, ::TypeString, ::TypeBlob. + +@see NodeType, upcast/downcast discussion in Node +*/ +NodeType Node::type() const +{ + return impl_->type(); +} + +/*! +@brief Is this a root node. + +@details +A root node has itself as a parent (it is not a child of any node). +Newly constructed nodes (before they are inserted into an ImageFile tree) start out as root nodes. +It is possible to temporarily create small trees that are unattached to any ImageFile. In these +temporary trees, the top-most node will be a root node. After the tree is attached to the ImageFile +tree, the only root node will be the pre-created one of the ImageTree (the one returned by +ImageFile::root). The concept of @em attachment is slightly larger than that of the parent-child +relationship (see Node::isAttached and CompressedVectorNode::CompressedVectorNode for more details). + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return true if this node is a root node. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see Node::parent, Node::isAttached, CompressedVectorNode::CompressedVectorNode +*/ +bool Node::isRoot() const +{ + return impl_->isRoot(); +} + +/*! +@brief Return parent of node, or self if a root node. + +@details +Nodes are organized into trees (acyclic graphs) with a distinguished node (the "top-most" node) +called the root node. A parent-child relationship is established between nodes to form a tree. Nodes +can have zero or one parent. Nodes with zero parents are called root nodes. + +In the API, if a node has zero parents it is represented by having itself as a parent. Due to the +set-once design of the API, a parent-child relationship cannot be modified once established. A child +node can be any of the 8 node types, but a parent node can only be one of the 3 container node types +(::TypeStructure, ::TypeVector, and ::TypeCompressedVector). Each parent-child link has a string +name (the elementName) associated with it (See Node::elementName for more details). More than one +tree can be formed at any given time. Typically small trees are temporarily constructed before +attachment to an ImageFile so that they will be written to the disk. + +@warning User algorithms that use this function to walk the tree must take care to handle the case +where a node is its own parent (it is a root node). Use Node::isRoot to avoid infinite loops or +infinite recursion. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return A smart Node handle referencing the parent node or this node if is a root node. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see Node::isRoot, Node::isAttached, CompressedVectorNode::CompressedVectorNode, Node::elementName +*/ +Node Node::parent() const +{ + return Node( impl_->parent() ); +} + +/*! +@brief Get absolute pathname of node. + +@details +Nodes are organized into trees (acyclic graphs) by a parent-child relationship between nodes. Each +parent-child relationship has an associated elementName string that is unique for a given parent. +Any node in a given tree can be identified by a sequence of elementNames of how to get to the node +from the root of the tree. An absolute pathname string that is formed by arranging this sequence of +elementNames separated by the "/" character with a leading "/" prepended. + +Some example absolute pathNames: "/data3D/0/points/153/cartesianX", "/data3D/0/points", +"/cameraImages/1/pose/rotation/w", and "/". These examples have probably been attached to an +ImageFile. Here is an example absolute pathName of a node in a pose tree that has not yet been +attached to an ImageFile: "/pose/rotation/w". + +A technical aside: the elementName of a root node does not appear in absolute pathnames, since the +"path" is between the staring node (the root) and the ending node. By convention, in this API, a +root node has the empty string ("") as its elementName. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The absolute path name of the node. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see Node::elementName, Node::parent, Node::isRoot +*/ +ustring Node::pathName() const +{ + return impl_->pathName(); +} + +/*! +@brief Get element name of node. + +@details +The elementName is a string associated with each parent-child link between nodes. For a given +parent, the elementName uniquely identifies each of its children. Thus, any node in a tree can be +identified by a sequence of elementNames that form a path from the tree's root node (see +Node::pathName for more details). + +Three types of nodes (the container node types) can be parents: StructureNode, VectorNode, and +CompressedVectorNode. The children of a StructureNode are explicitly given unique elementNames when +they are attached to the parent (using StructureNode::set). The children of VectorNode and +CompressedVectorNode are implicitly given elementNames based on their position in the list (starting +at "0"). In a CompressedVectorNode, the elementName can become quite large: "1000000000" or more. +However in a CompressedVectorNode, the elementName string is not stored in the file and is deduced +by the position of the child. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The element name of the node, or "" if a root node. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see Node::pathName, Node::parent, Node::isRoot +*/ +ustring Node::elementName() const +{ + return impl_->elementName(); +} + +/*! +@brief Get the ImageFile that was declared as the destination for the node when it was created. + +@details +The first argument of the constructors of each of the 8 types of nodes is an ImageFile that +indicates which ImageFile the node will eventually be attached to. This function returns that +constructor argument. It is an error to attempt to attach the node to a different ImageFile. However +it is not an error to not attach the node to any ImageFile (it's just wasteful). Use +Node::isAttached to check if the node actually did get attached. + +@post No visible object state is modified. + +@return The ImageFile that was declared as the destination for the node when it was created. + +@see Node::isAttached, StructureNode::StructureNode(), VectorNode::VectorNode(), +CompressedVectorNode::CompressedVectorNode(), IntegerNode::IntegerNode(), +ScaledIntegerNode::ScaledIntegerNode(), FloatNode::FloatNode(), StringNode::StringNode(), +BlobNode::BlobNode() +*/ +ImageFile Node::destImageFile() const +{ + return ImageFile( impl_->destImageFile() ); +} + +/*! +@brief Has node been attached into the tree of an ImageFile. + +@details +Nodes are attached into an ImageFile tree by inserting them as children (directly or indirectly) of +the ImageFile's root node. Nodes can also be attached to an ImageFile if they are used in the @c +codecs or @c prototype trees of an CompressedVectorNode that is attached. Attached nodes will be +saved to disk when the ImageFile is closed, and restored when the ImageFile is read back in from +disk. Unattached nodes will not be saved to disk. It is not recommended to create nodes that are not +eventually attached to the ImageFile. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible object state is modified. + +@return @c true if node is child of (or in codecs or prototype of a child CompressedVectorNode of) +the root node of an ImageFile. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see Node::destImageFile, ImageFile::root +*/ +bool Node::isAttached() const +{ + return impl_->isAttached(); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. + +@param [in] indent Number of spaces to indent all the printed lines of this object. +@param [in] os Output stream to print on. + +@details +All objects in the E57 Foundation API (with exception of E57Exception) support a dump() function. +These functions print out to the console a detailed listing of the internal state of objects. The +content of these printouts is not documented, and is really of interest only to implementation +developers/maintainers or the really adventurous users. In implementations of the API other than the +Reference Implementation, the dump() functions may produce no output (although the functions should +still be defined). The output format may change from version to version. + +@post No visible object state is modified. + +@throw No E57Exceptions +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void Node::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void Node::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif + +/*! +@brief Test if two node handles refer to the same underlying node + +@param [in] n2 The node to compare this node with + +@post No visible object state is modified. + +@return @c true if node handles refer to the same underlying node. + +@throw No E57Exceptions +*/ +bool Node::operator==( const Node &n2 ) const +{ + return ( impl_ == n2.impl_ ); +} + +/*! +@brief Test if two node handles refer to different underlying nodes + +@param [in] n2 The node to compare this node with + +@post No visible object state is modified. + +@return @c true if node handles refer to different underlying nodes. + +@throw No E57Exceptions +*/ +bool Node::operator!=( const Node &n2 ) const +{ + return ( impl_ != n2.impl_ ); +} + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +Node::Node( NodeImplSharedPtr ni ) : impl_( ni ) +{ +} +/// @endcond diff --git a/src/3rdParty/libE57Format/src/NodeImpl.cpp b/src/3rdParty/libE57Format/src/NodeImpl.cpp index 8cb2a5032f329..c006e776997ae 100644 --- a/src/3rdParty/libE57Format/src/NodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/NodeImpl.cpp @@ -28,24 +28,28 @@ #include "NodeImpl.h" #include "ImageFileImpl.h" #include "SourceDestBufferImpl.h" +#include "StringFunctions.h" #include "VectorNodeImpl.h" using namespace e57; -NodeImpl::NodeImpl( ImageFileImplWeakPtr destImageFile ) : destImageFile_( destImageFile ), isAttached_( false ) +NodeImpl::NodeImpl( ImageFileImplWeakPtr destImageFile ) : + destImageFile_( destImageFile ), isAttached_( false ) { - checkImageFileOpen( __FILE__, __LINE__, - static_cast( __FUNCTION__ ) ); // does checking for all node type ctors + checkImageFileOpen( + __FILE__, __LINE__, + static_cast( __FUNCTION__ ) ); // does checking for all node type ctors } -void NodeImpl::checkImageFileOpen( const char *srcFileName, int srcLineNumber, const char *srcFunctionName ) const +void NodeImpl::checkImageFileOpen( const char *srcFileName, int srcLineNumber, + const char *srcFunctionName ) const { - /// Throw an exception if destImageFile (destImageFile_) isn't open + // Throw an exception if destImageFile (destImageFile_) isn't open ImageFileImplSharedPtr destImageFile( destImageFile_ ); if ( !destImageFile->isOpen() ) { - throw E57Exception( E57_ERROR_IMAGEFILE_NOT_OPEN, "fileName=" + destImageFile->fileName(), srcFileName, - srcLineNumber, srcFunctionName ); + throw E57Exception( ErrorImageFileNotOpen, "fileName=" + destImageFile->fileName(), + srcFileName, srcLineNumber, srcFunctionName ); } } @@ -54,7 +58,7 @@ bool NodeImpl::isRoot() const checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); return parent_.expired(); -}; +} NodeImplSharedPtr NodeImpl::parent() { @@ -62,7 +66,7 @@ NodeImplSharedPtr NodeImpl::parent() if ( isRoot() ) { - /// If is root, then has self as parent (by convention) + // If is root, then has self as parent (by convention) return shared_from_this(); } @@ -100,12 +104,12 @@ ustring NodeImpl::relativePathName( const NodeImplSharedPtr &origin, ustring chi if ( isRoot() ) { - /// Got to top and didn't find origin, must be error - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, - "this->elementName=" + this->elementName() + " childPathName=" + childPathName ); + // Got to top and didn't find origin, must be error + throw E57_EXCEPTION2( ErrorInternal, "this->elementName=" + this->elementName() + + " childPathName=" + childPathName ); } - /// Assemble relativePathName from right to left, recursively + // Assemble relativePathName from right to left, recursively NodeImplSharedPtr p( parent_ ); if ( childPathName.empty() ) @@ -125,7 +129,7 @@ ustring NodeImpl::elementName() const ImageFileImplSharedPtr NodeImpl::destImageFile() { - /// don't checkImageFileOpen + // don't checkImageFileOpen return ImageFileImplSharedPtr( destImageFile_ ); } @@ -138,15 +142,14 @@ bool NodeImpl::isAttached() const void NodeImpl::setAttachedRecursive() { - /// Non-terminal node types (Structure, Vector, CompressedVector) will - /// override this virtual function, to mark their children, codecs, - /// prototypes + // Non-terminal node types (Structure, Vector, CompressedVector) will override this virtual + // function, to mark their children, codecs, prototypes isAttached_ = true; } ustring NodeImpl::imageFileName() const { - /// don't checkImageFileOpen + // don't checkImageFileOpen ImageFileImplSharedPtr imf( destImageFile_ ); return imf->fileName(); @@ -154,27 +157,28 @@ ustring NodeImpl::imageFileName() const void NodeImpl::setParent( NodeImplSharedPtr parent, const ustring &elementName ) { - /// don't checkImageFileOpen - - /// First check if our parent_ is already set, throw - /// E57_ERROR_ALREADY_HAS_PARENT The isAttached_ condition is to catch two - /// errors: - /// 1) if user attempts to use the ImageFile root as a child (e.g. - /// root.set("x", root)) 2) if user attempts to reuse codecs or prototype - /// trees of a CompressedVectorNode - /// ??? what if CV not attached yet? + // don't checkImageFileOpen + + // First check if our parent_ is already set, throw + // ErrorAlreadyHasParent The isAttached_ condition is to catch two + // errors: + // 1) if user attempts to use the ImageFile root as a child (e.g. + // root.set("x", root)) 2) if user attempts to reuse codecs or prototype + // trees of a CompressedVectorNode + // ??? what if CV not attached yet? if ( !parent_.expired() || isAttached_ ) { - /// ??? does caller do setParent first, so state is not messed up when - /// throw? - throw E57_EXCEPTION2( E57_ERROR_ALREADY_HAS_PARENT, - "this->pathName=" + this->pathName() + " newParent->pathName=" + parent->pathName() ); + // ??? does caller do setParent first, so state is not messed up when + // throw? + throw E57_EXCEPTION2( ErrorAlreadyHasParent, + "this->pathName=" + this->pathName() + + " newParent->pathName=" + parent->pathName() ); } parent_ = parent; elementName_ = elementName; - /// If parent is attached then we are attached (and all of our children) + // If parent is attached then we are attached (and all of our children) if ( parent->isAttached() ) { setAttachedRecursive(); @@ -183,7 +187,7 @@ void NodeImpl::setParent( NodeImplSharedPtr parent, const ustring &elementName ) NodeImplSharedPtr NodeImpl::getRoot() { - /// don't checkImageFileOpen + // don't checkImageFileOpen NodeImplSharedPtr p( shared_from_this() ); while ( !p->isRoot() ) { @@ -196,92 +200,90 @@ NodeImplSharedPtr NodeImpl::getRoot() //??? use visitor? bool NodeImpl::isTypeConstrained() { - /// don't checkImageFileOpen - /// A node is type constrained if any of its parents is an homo VECTOR or - /// COMPRESSED_VECTOR with more than one child + // don't checkImageFileOpen + // A node is type constrained if any of its parents is an homo VECTOR or COMPRESSED_VECTOR with + // more than one child NodeImplSharedPtr p( shared_from_this() ); while ( !p->isRoot() ) { - /// We have a parent since we are not root + // We have a parent since we are not root p = NodeImplSharedPtr( p->parent_ ); //??? check if bad ptr? switch ( p->type() ) { - case E57_VECTOR: + case TypeVector: { - /// Downcast to shared_ptr + // Downcast to shared_ptr std::shared_ptr ai( std::static_pointer_cast( p ) ); - /// If homogeneous vector and have more than one child, then can't - /// change them + // If homogeneous vector and have more than one child, then can't change them if ( !ai->allowHeteroChildren() && ai->childCount() > 1 ) { return ( true ); } } break; - case E57_COMPRESSED_VECTOR: - /// Can't make any type changes to CompressedVector prototype. ??? - /// what if hasn't been written to yet + case TypeCompressedVector: + // Can't make any type changes to CompressedVector prototype. ??? + // what if hasn't been written to yet return ( true ); default: break; } } - /// Didn't find any constraining VECTORs or COMPRESSED_VECTORs in path above - /// us, so our type is not constrained. + // Didn't find any constraining VECTORs or COMPRESSED_VECTORs in path above us, so our type is + // not constrained. return ( false ); } NodeImplSharedPtr NodeImpl::get( const ustring &pathName ) { - /// This is common virtual function for terminal E57 element types: Integer, - /// ScaledInteger, Float, Blob. The non-terminal types override this virtual - /// function. Only absolute pathNames make any sense here, because the - /// terminal types can't have children, so relative pathNames are illegal. + // This is common virtual function for terminal E57 element types: Integer, ScaledInteger, Float, + // Blob. The non-terminal types override this virtual function. Only absolute pathNames make any + // sense here, because the terminal types can't have children, so relative pathNames are illegal. -#ifdef E57_DEBUG +#ifdef VALIDATE_BASIC _verifyPathNameAbsolute( pathName ); #endif NodeImplSharedPtr root = _verifyAndGetRoot(); - /// Forward call to the non-terminal root node + // Forward call to the non-terminal root node return root->get( pathName ); } void NodeImpl::set( const ustring &pathName, NodeImplSharedPtr ni, bool autoPathCreate ) { - /// This is common virtual function for terminal E57 element types: Integer, - /// ScaledInteger, Float, Blob. The non-terminal types override this virtual - /// function. Only absolute pathNames make any sense here, because the - /// terminal types can't have children, so relative pathNames are illegal. + // This is common virtual function for terminal E57 element types: Integer, ScaledInteger, + // Float, Blob. The non-terminal types override this virtual function. Only absolute pathNames + // make any sense here, because the terminal types can't have children, so relative pathNames are + // illegal. -#ifdef E57_DEBUG +#ifdef VALIDATE_BASIC _verifyPathNameAbsolute( pathName ); #endif NodeImplSharedPtr root = _verifyAndGetRoot(); - /// Forward call to the non-terminal root node + // Forward call to the non-terminal root node root->set( pathName, ni, autoPathCreate ); } void NodeImpl::set( const StringList & /*fields*/, unsigned /*level*/, NodeImplSharedPtr /*ni*/, bool /*autoPathCreate*/ ) { - /// If get here, then tried to call set(fields...) on NodeImpl that wasn't a - /// StructureNodeImpl, so that's an error - throw E57_EXCEPTION1( E57_ERROR_BAD_PATH_NAME ); //??? + // If get here, then tried to call set(fields...) on NodeImpl that wasn't a StructureNodeImpl, + // so that's an error + throw E57_EXCEPTION1( ErrorBadPathName ); //??? } void NodeImpl::checkBuffers( const std::vector &sdbufs, bool allowMissing ) //??? convert sdbufs to vector of shared_ptr { - /// this node is prototype of CompressedVector + // this node is prototype of CompressedVector - /// don't checkImageFileOpen + // don't checkImageFileOpen StringSet pathNames; @@ -289,42 +291,41 @@ void NodeImpl::checkBuffers( const std::vector &sdbufs, { ustring pathName = sdbufs.at( i ).impl()->pathName(); - /// Check that all buffers are same size + // Check that all buffers are same size if ( sdbufs.at( i ).impl()->capacity() != sdbufs.at( 0 ).impl()->capacity() ) { - throw E57_EXCEPTION2( E57_ERROR_BUFFER_SIZE_MISMATCH, - "this->pathName=" + this->pathName() + " sdbuf.pathName=" + pathName + - " firstCapacity=" + toString( sdbufs.at( 0 ).impl()->capacity() ) + - " secondCapacity=" + toString( sdbufs.at( i ).impl()->capacity() ) ); + throw E57_EXCEPTION2( + ErrorBufferSizeMismatch, + "this->pathName=" + this->pathName() + " sdbuf.pathName=" + pathName + + " firstCapacity=" + toString( sdbufs.at( 0 ).impl()->capacity() ) + + " secondCapacity=" + toString( sdbufs.at( i ).impl()->capacity() ) ); } - /// Add each pathName to set, error if already in set (a duplicate - /// pathName in sdbufs) + // Add each pathName to set, error if already in set (a duplicate pathName in sdbufs) if ( !pathNames.insert( pathName ).second ) { - throw E57_EXCEPTION2( E57_ERROR_BUFFER_DUPLICATE_PATHNAME, - "this->pathName=" + this->pathName() + " sdbuf.pathName=" + pathName ); + throw E57_EXCEPTION2( ErrorBufferDuplicatePathName, "this->pathName=" + this->pathName() + + " sdbuf.pathName=" + pathName ); } - /// Check no bad fields in sdbufs + // Check no bad fields in sdbufs if ( !isDefined( pathName ) ) { - throw E57_EXCEPTION2( E57_ERROR_PATH_UNDEFINED, - "this->pathName=" + this->pathName() + " sdbuf.pathName=" + pathName ); + throw E57_EXCEPTION2( ErrorPathUndefined, "this->pathName=" + this->pathName() + + " sdbuf.pathName=" + pathName ); } } if ( !allowMissing ) { - /// Traverse tree recursively, checking that all nodes are listed in - /// sdbufs + // Traverse tree recursively, checking that all nodes are listed in sdbufs checkLeavesInSet( pathNames, shared_from_this() ); } } bool NodeImpl::findTerminalPosition( const NodeImplSharedPtr &target, uint64_t &countFromLeft ) { - /// don't checkImageFileOpen + // don't checkImageFileOpen if ( this == &*target ) //??? ok? { @@ -333,11 +334,11 @@ bool NodeImpl::findTerminalPosition( const NodeImplSharedPtr &target, uint64_t & switch ( type() ) { - case E57_STRUCTURE: + case TypeStructure: { auto sni = static_cast( this ); - /// Recursively visit child nodes + // Recursively visit child nodes int64_t childCount = sni->childCount(); for ( int64_t i = 0; i < childCount; ++i ) { @@ -349,11 +350,11 @@ bool NodeImpl::findTerminalPosition( const NodeImplSharedPtr &target, uint64_t & } break; - case E57_VECTOR: + case TypeVector: { auto vni = static_cast( this ); - /// Recursively visit child nodes + // Recursively visit child nodes int64_t childCount = vni->childCount(); for ( int64_t i = 0; i < childCount; ++i ) { @@ -365,14 +366,14 @@ bool NodeImpl::findTerminalPosition( const NodeImplSharedPtr &target, uint64_t & } break; - case E57_COMPRESSED_VECTOR: + case TypeCompressedVector: break; //??? for now, don't search into contents of compressed vector - case E57_INTEGER: - case E57_SCALED_INTEGER: - case E57_FLOAT: - case E57_STRING: - case E57_BLOB: + case TypeInteger: + case TypeScaledInteger: + case TypeFloat: + case TypeString: + case TypeBlob: countFromLeft++; break; } @@ -380,20 +381,22 @@ bool NodeImpl::findTerminalPosition( const NodeImplSharedPtr &target, uint64_t & return ( false ); } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void NodeImpl::dump( int indent, std::ostream &os ) const { - /// don't checkImageFileOpen + // don't checkImageFileOpen os << space( indent ) << "elementName: " << elementName_ << std::endl; os << space( indent ) << "isAttached: " << isAttached_ << std::endl; os << space( indent ) << "path: " << pathName() << std::endl; } +#endif +#ifdef VALIDATE_BASIC bool NodeImpl::_verifyPathNameAbsolute( const ustring &inPathName ) { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); - /// Parse to determine if pathName is absolute + // Parse to determine if pathName is absolute bool isRelative = false; std::vector fields; ImageFileImplSharedPtr imf( destImageFile_ ); @@ -401,30 +404,31 @@ bool NodeImpl::_verifyPathNameAbsolute( const ustring &inPathName ) imf->pathNameParse( inPathName, isRelative, fields ); // throws if bad pathName - /// If not an absolute path name, have error + // If not an absolute path name, have error if ( isRelative ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_PATH_NAME, "this->pathName=" + this->pathName() + " pathName=" + inPathName ); + throw E57_EXCEPTION2( ErrorBadPathName, + "this->pathName=" + this->pathName() + " pathName=" + inPathName ); } - return isRelative; + return false; } #endif NodeImplSharedPtr NodeImpl::_verifyAndGetRoot() { - /// Find root of the tree + // Find root of the tree NodeImplSharedPtr root( shared_from_this()->getRoot() ); - /// Check to make sure root node is non-terminal type (otherwise have stack - /// overflow). + // Check to make sure root node is non-terminal type (otherwise have stack overflow). switch ( root->type() ) { - case E57_STRUCTURE: - case E57_VECTOR: //??? COMPRESSED_VECTOR? + case TypeStructure: + case TypeVector: //??? COMPRESSED_VECTOR? break; default: - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "root invalid for this->pathName=" + this->pathName() ); + throw E57_EXCEPTION2( ErrorInternal, + "root invalid for this->pathName=" + this->pathName() ); } return root; diff --git a/src/3rdParty/libE57Format/src/NodeImpl.h b/src/3rdParty/libE57Format/src/NodeImpl.h index 177b1ef209920..dc61c5dc06fb2 100644 --- a/src/3rdParty/libE57Format/src/NodeImpl.h +++ b/src/3rdParty/libE57Format/src/NodeImpl.h @@ -31,19 +31,21 @@ namespace e57 { - class CheckedFile; class NodeImpl : public std::enable_shared_from_this { public: virtual NodeType type() const = 0; - void checkImageFileOpen( const char *srcFileName, int srcLineNumber, const char *srcFunctionName ) const; + void checkImageFileOpen( const char *srcFileName, int srcLineNumber, + const char *srcFunctionName ) const; virtual bool isTypeEquivalent( NodeImplSharedPtr ni ) = 0; + bool isRoot() const; NodeImplSharedPtr parent(); ustring pathName() const; - ustring relativePathName( const NodeImplSharedPtr &origin, ustring childPathName = ustring() ) const; + ustring relativePathName( const NodeImplSharedPtr &origin, + ustring childPathName = ustring() ) const; ustring elementName() const; ImageFileImplSharedPtr destImageFile(); @@ -56,8 +58,10 @@ namespace e57 bool isTypeConstrained(); virtual NodeImplSharedPtr get( const ustring &pathName ); - virtual void set( const ustring &pathName, NodeImplSharedPtr ni, bool autoPathCreate = false ); - virtual void set( const StringList &fields, unsigned level, NodeImplSharedPtr ni, bool autoPathCreate = false ); + virtual void set( const ustring &pathName, NodeImplSharedPtr ni, + bool autoPathCreate = false ); + virtual void set( const StringList &fields, unsigned level, NodeImplSharedPtr ni, + bool autoPathCreate = false ); virtual void checkLeavesInSet( const StringSet &pathNames, NodeImplSharedPtr origin ) = 0; void checkBuffers( const std::vector &sdbufs, bool allowMissing ); @@ -68,12 +72,12 @@ namespace e57 virtual ~NodeImpl() = default; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT virtual void dump( int indent = 0, std::ostream &os = std::cout ) const; #endif private: -#ifdef E57_DEBUG +#ifdef VALIDATE_BASIC bool _verifyPathNameAbsolute( const ustring &inPathName ); #endif @@ -85,12 +89,13 @@ namespace e57 friend class Decoder; friend class Encoder; - NodeImpl( ImageFileImplWeakPtr destImageFile ); - NodeImpl &operator=( NodeImpl &n ); + explicit NodeImpl( ImageFileImplWeakPtr destImageFile ); + virtual NodeImplSharedPtr lookup( const ustring & /*pathName*/ ) { - return NodeImplSharedPtr(); + return {}; } + NodeImplSharedPtr getRoot(); ImageFileImplWeakPtr destImageFile_; diff --git a/src/3rdParty/libE57Format/src/Packet.cpp b/src/3rdParty/libE57Format/src/Packet.cpp index 2f3ae672d36af..cdfef47834031 100644 --- a/src/3rdParty/libE57Format/src/Packet.cpp +++ b/src/3rdParty/libE57Format/src/Packet.cpp @@ -29,13 +29,12 @@ #include "CheckedFile.h" #include "Packet.h" +#include "StringFunctions.h" using namespace e57; -struct IndexPacket +struct IndexPacketHeader { - static constexpr unsigned MAX_ENTRIES = 2048; - const uint8_t packetType = INDEX_PACKET; uint8_t packetFlags = 0; // flag bitfields @@ -43,6 +42,13 @@ struct IndexPacket uint16_t entryCount = 0; uint8_t indexLevel = 0; uint8_t reserved1[9] = {}; // must be zero +}; + +struct IndexPacket +{ + IndexPacketHeader header; + + static constexpr unsigned MAX_ENTRIES = 2048; struct IndexPacketEntry { @@ -50,9 +56,10 @@ struct IndexPacket uint64_t chunkPhysicalOffset = 0; } entries[MAX_ENTRIES]; - void verify( unsigned bufferLength = 0, uint64_t totalRecordCount = 0, uint64_t fileSize = 0 ) const; + void verify( unsigned bufferLength = 0, uint64_t totalRecordCount = 0, + uint64_t fileSize = 0 ) const; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const; #endif }; @@ -66,7 +73,7 @@ struct EmptyPacketHeader void verify( unsigned bufferLength = 0 ) const; //???use -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const; #endif }; @@ -74,62 +81,64 @@ struct EmptyPacketHeader //============================================================================= // PacketReadCache -PacketReadCache::PacketReadCache( CheckedFile *cFile, unsigned packetCount ) : cFile_( cFile ), entries_( packetCount ) +PacketReadCache::PacketReadCache( CheckedFile *cFile, unsigned packetCount ) : + cFile_( cFile ), entries_( packetCount ) { if ( packetCount == 0 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "packetCount=" + toString( packetCount ) ); + throw E57_EXCEPTION2( ErrorInternal, "packetCount=" + toString( packetCount ) ); } } std::unique_ptr PacketReadCache::lock( uint64_t packetLogicalOffset, char *&pkt ) { -#ifdef E57_MAX_VERBOSE - std::cout << "PacketReadCache::lock() called, packetLogicalOffset=" << packetLogicalOffset << std::endl; +#ifdef E57_VERBOSE + std::cout << "PacketReadCache::lock() called, packetLogicalOffset=" << packetLogicalOffset + << std::endl; #endif - /// Only allow one locked packet at a time. + // Only allow one locked packet at a time. if ( lockCount_ > 0 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "lockCount=" + toString( lockCount_ ) ); + throw E57_EXCEPTION2( ErrorInternal, "lockCount=" + toString( lockCount_ ) ); } - /// Offset can't be 0 + // Offset can't be 0 if ( packetLogicalOffset == 0 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "packetLogicalOffset=" + toString( packetLogicalOffset ) ); + throw E57_EXCEPTION2( ErrorInternal, + "packetLogicalOffset=" + toString( packetLogicalOffset ) ); } - /// Linear scan for matching packet offset in cache + // Linear scan for matching packet offset in cache for ( unsigned i = 0; i < entries_.size(); ++i ) { auto &entry = entries_[i]; if ( packetLogicalOffset == entry.logicalOffset_ ) { - /// Found a match, so don't have to read anything -#ifdef E57_MAX_VERBOSE + // Found a match, so don't have to read anything +#ifdef E57_VERBOSE std::cout << " Found matching cache entry, index=" << i << std::endl; #endif - /// Mark entry with current useCount (keeps track of age of entry). + // Mark entry with current useCount (keeps track of age of entry). entry.lastUsed_ = ++useCount_; - /// Publish buffer address to caller + // Publish buffer address to caller pkt = entry.buffer_; - /// Create lock so we are sure that we will be unlocked when use is - /// finished. + // Create lock so we are sure that we will be unlocked when use is finished. std::unique_ptr plock( new PacketLock( this, i ) ); - /// Increment cache lock just before return + // Increment cache lock just before return ++lockCount_; return plock; } } - /// Get here if didn't find a match already in cache. + // Get here if didn't find a match already in cache. - /// Find least recently used (LRU) packet buffer + // Find least recently used (LRU) packet buffer unsigned oldestEntry = 0; unsigned oldestUsed = entries_.at( 0 ).lastUsed_; @@ -143,19 +152,19 @@ std::unique_ptr PacketReadCache::lock( uint64_t packetLogicalOffset, oldestUsed = entry.lastUsed_; } } -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " Oldest entry=" << oldestEntry << " lastUsed=" << oldestUsed << std::endl; #endif readPacket( oldestEntry, packetLogicalOffset ); - /// Publish buffer address to caller + // Publish buffer address to caller pkt = entries_[oldestEntry].buffer_; - /// Create lock so we are sure we will be unlocked when use is finished. + // Create lock so we are sure we will be unlocked when use is finished. std::unique_ptr plock( new PacketLock( this, oldestEntry ) ); - /// Increment cache lock just before return + // Increment cache lock just before return ++lockCount_; return plock; @@ -163,15 +172,16 @@ std::unique_ptr PacketReadCache::lock( uint64_t packetLogicalOffset, void PacketReadCache::unlock( unsigned cacheIndex ) { - (void)cacheIndex; //??? why lockedEntry not used? -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "PacketReadCache::unlock() called, cacheIndex=" << cacheIndex << std::endl; +#else + UNUSED( cacheIndex ); #endif if ( lockCount_ != 1 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "lockCount=" + toString( lockCount_ ) ); + throw E57_EXCEPTION2( ErrorInternal, "lockCount=" + toString( lockCount_ ) ); } --lockCount_; @@ -179,35 +189,34 @@ void PacketReadCache::unlock( unsigned cacheIndex ) void PacketReadCache::readPacket( unsigned oldestEntry, uint64_t packetLogicalOffset ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "PacketReadCache::readPacket() called, oldestEntry=" << oldestEntry << " packetLogicalOffset=" << packetLogicalOffset << std::endl; #endif - /// Read header of packet first to get length. Use EmptyPacketHeader since - /// it has the fields common to all packets. + // Read header of packet first to get length. Use EmptyPacketHeader since it has the fields + // common to all packets. EmptyPacketHeader header; cFile_->seek( packetLogicalOffset, CheckedFile::Logical ); cFile_->read( reinterpret_cast( &header ), sizeof( header ) ); - /// Can't verify packet header here, because it is not really an - /// EmptyPacketHeader. + // Can't verify packet header here, because it is not really an EmptyPacketHeader. unsigned packetLength = header.packetLogicalLengthMinus1 + 1; - /// Be paranoid about packetLength before read + // Be paranoid about packetLength before read if ( packetLength > DATA_PACKET_MAX ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetLength=" + toString( packetLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "packetLength=" + toString( packetLength ) ); } auto &entry = entries_.at( oldestEntry ); - /// Now read in whole packet into preallocated buffer_. Note buffer is + // Now read in whole packet into preallocated buffer_. Note buffer is cFile_->seek( packetLogicalOffset, CheckedFile::Logical ); cFile_->read( entry.buffer_, packetLength ); - /// Verify that packet is good. + // Verify that packet is good. switch ( header.packetType ) { case DATA_PACKET: @@ -215,7 +224,7 @@ void PacketReadCache::readPacket( unsigned oldestEntry, uint64_t packetLogicalOf auto dpkt = reinterpret_cast( entry.buffer_ ); dpkt->verify( packetLength ); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " data packet:" << std::endl; dpkt->dump( 4 ); //??? #endif @@ -226,7 +235,7 @@ void PacketReadCache::readPacket( unsigned oldestEntry, uint64_t packetLogicalOf auto ipkt = reinterpret_cast( entry.buffer_ ); ipkt->verify( packetLength ); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " index packet:" << std::endl; ipkt->dump( 4 ); //??? #endif @@ -237,24 +246,24 @@ void PacketReadCache::readPacket( unsigned oldestEntry, uint64_t packetLogicalOf auto hp = reinterpret_cast( entry.buffer_ ); hp->verify( packetLength ); -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << " empty packet:" << std::endl; hp->dump( 4 ); //??? #endif } break; default: - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "packetType=" + toString( header.packetType ) ); + throw E57_EXCEPTION2( ErrorInternal, "packetType=" + toString( header.packetType ) ); } entry.logicalOffset_ = packetLogicalOffset; - /// Mark entry with current useCount (keeps track of age of entry). - /// This is a cache, so a small hiccup when useCount_ overflows won't hurt. + // Mark entry with current useCount (keeps track of age of entry). + // This is a cache, so a small hiccup when useCount_ overflows won't hurt. entry.lastUsed_ = ++useCount_; } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void PacketReadCache::dump( int indent, std::ostream &os ) { os << space( indent ) << "lockCount: " << lockCount_ << std::endl; @@ -290,9 +299,9 @@ void PacketReadCache::dump( int indent, std::ostream &os ) break; default: throw E57_EXCEPTION2( - E57_ERROR_INTERNAL, - "packetType=" + - toString( reinterpret_cast( entries_.at( i ).buffer_ )->packetType ) ); + ErrorInternal, "packetType=" + toString( reinterpret_cast( + entries_.at( i ).buffer_ ) + ->packetType ) ); } } } @@ -302,21 +311,22 @@ void PacketReadCache::dump( int indent, std::ostream &os ) //============================================================================= // PacketLock -PacketLock::PacketLock( PacketReadCache *cache, unsigned cacheIndex ) : cache_( cache ), cacheIndex_( cacheIndex ) +PacketLock::PacketLock( PacketReadCache *cache, unsigned cacheIndex ) : + cache_( cache ), cacheIndex_( cacheIndex ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "PacketLock() called" << std::endl; #endif } PacketLock::~PacketLock() { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "~PacketLock() called" << std::endl; #endif try { - /// Note cache must live longer than lock, this is reasonable assumption. + // Note cache must live longer than lock, this is reasonable assumption. cache_->unlock( cacheIndex_ ); } catch ( ... ) @@ -330,8 +340,7 @@ PacketLock::~PacketLock() DataPacketHeader::DataPacketHeader() { - /// Double check that packet struct is correct length. Watch out for RTTI - /// increasing the size. + // Double check that packet struct is correct length. Watch out for RTTI increasing the size. static_assert( sizeof( DataPacketHeader ) == 6, "Unexpected size of DataPacketHeader" ); } @@ -344,54 +353,59 @@ void DataPacketHeader::reset() void DataPacketHeader::verify( unsigned bufferLength ) const { - /// Verify that packet is correct type + // Verify that packet is correct type if ( packetType != DATA_PACKET ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetType=" + toString( packetType ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, + "expected Data; packetType=" + toString( packetType ) ); } - /// ??? check reserved flags zero? + // ??? check reserved flags zero? - /// Check packetLength is at least large enough to hold header + // Check packetLength is at least large enough to hold header unsigned packetLength = packetLogicalLengthMinus1 + 1; if ( packetLength < sizeof( *this ) ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetLength=" + toString( packetLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "DATA; packetLength=" + toString( packetLength ) ); } - /// Check packet length is multiple of 4 + // Check packet length is multiple of 4 if ( packetLength % 4 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetLength=" + toString( packetLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "DATA; packetLength=" + toString( packetLength ) ); } - /// Check actual packet length is large enough. + // Check actual packet length is large enough. if ( bufferLength > 0 && packetLength > bufferLength ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, - "packetLength=" + toString( packetLength ) + " bufferLength=" + toString( bufferLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "DATA; packetLength=" + toString( packetLength ) + + " bufferLength=" + toString( bufferLength ) ); } - /// Make sure there is at least one entry in packet ??? 0 record cvect - /// allowed? + // Make sure there is at least one entry in packet ??? 0 record cvect + // allowed? if ( bytestreamCount == 0 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "bytestreamCount=" + toString( bytestreamCount ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, + "DATA; bytestreamCount=" + toString( bytestreamCount ) ); } - /// Check packet is at least long enough to hold bytestreamBufferLength array - if ( sizeof( DataPacketHeader ) + 2 * bytestreamCount > packetLength ) + // Check packet is at least long enough to hold bytestreamBufferLength array + if ( ( sizeof( DataPacketHeader ) + 2 * bytestreamCount ) > packetLength ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetLength=" + toString( packetLength ) + - " bytestreamCount=" + toString( bytestreamCount ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, + "DATA; packetLength=" + toString( packetLength ) + + " bytestreamCount=" + toString( bytestreamCount ) ); } } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void DataPacketHeader::dump( int indent, std::ostream &os ) const { - os << space( indent ) << "packetType: " << static_cast( packetType ) << std::endl; - os << space( indent ) << "packetFlags: " << static_cast( packetFlags ) << std::endl; + os << space( indent ) << "packetType: " << static_cast( packetType ) + << std::endl; + os << space( indent ) << "packetFlags: " << static_cast( packetFlags ) + << std::endl; os << space( indent ) << "packetLogicalLengthMinus1: " << packetLogicalLengthMinus1 << std::endl; os << space( indent ) << "bytestreamCount: " << bytestreamCount << std::endl; } @@ -402,9 +416,8 @@ void DataPacketHeader::dump( int indent, std::ostream &os ) const DataPacket::DataPacket() { - /// Double check that packet struct is correct length. Watch out for RTTI - /// increasing the size. - static_assert( sizeof( DataPacket ) == 64 * 1024, "Unexpected size of DataPacket" ); + // Double check that packet struct is correct length. Watch out for RTTI increasing the size. + static_assert( sizeof( DataPacket ) == ( 64 * 1024 ), "Unexpected size of DataPacket" ); } void DataPacket::verify( unsigned bufferLength ) const @@ -413,12 +426,12 @@ void DataPacket::verify( unsigned bufferLength ) const // checking? need to check // file version#? - /// Verify header is good + // Verify header is good auto hp = reinterpret_cast( this ); hp->verify( bufferLength ); - /// Calc sum of lengths of each bytestream buffer in this packet + // Calc sum of lengths of each bytestream buffer in this packet auto bsbLength = reinterpret_cast( &payload[0] ); unsigned totalStreamByteCount = 0; @@ -427,90 +440,93 @@ void DataPacket::verify( unsigned bufferLength ) const totalStreamByteCount += bsbLength[i]; } - /// Calc size of packet needed + // Calc size of packet needed const unsigned packetLength = header.packetLogicalLengthMinus1 + 1; - const unsigned needed = sizeof( DataPacketHeader ) + 2 * header.bytestreamCount + totalStreamByteCount; -#ifdef E57_MAX_VERBOSE + const unsigned needed = + sizeof( DataPacketHeader ) + 2 * header.bytestreamCount + totalStreamByteCount; +#ifdef E57_VERBOSE std::cout << "needed=" << needed << " actual=" << packetLength << std::endl; //??? #endif - /// If needed is not with 3 bytes of actual packet size, have an error + // If needed is not with 3 bytes of actual packet size, have an error if ( needed > packetLength || needed + 3 < packetLength ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, - "needed=" + toString( needed ) + "packetLength=" + toString( packetLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "DATA; needed=" + toString( needed ) + + " packetLength=" + toString( packetLength ) ); } - /// Verify that padding at end of packet is zero + // Verify that padding at end of packet is zero for ( unsigned i = needed; i < packetLength; i++ ) { if ( reinterpret_cast( this )[i] != 0 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "i=" + toString( i ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "DATA; i=" + toString( i ) ); } } } char *DataPacket::getBytestream( unsigned bytestreamNumber, unsigned &byteCount ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "getBytestream called, bytestreamNumber=" << bytestreamNumber << std::endl; #endif - /// Verify that packet is correct type + // Verify that packet is correct type if ( header.packetType != DATA_PACKET ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetType=" + toString( header.packetType ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "packetType=" + toString( header.packetType ) ); } - /// Check bytestreamNumber in bounds + // Check bytestreamNumber in bounds if ( bytestreamNumber >= header.bytestreamCount ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "bytestreamNumber=" + toString( bytestreamNumber ) + - "bytestreamCount=" + toString( header.bytestreamCount ) ); + throw E57_EXCEPTION2( ErrorInternal, + "bytestreamNumber=" + toString( bytestreamNumber ) + + "bytestreamCount=" + toString( header.bytestreamCount ) ); } - /// Calc positions in packet + // Calc positions in packet auto bsbLength = reinterpret_cast( &payload[0] ); auto streamBase = reinterpret_cast( &bsbLength[header.bytestreamCount] ); - /// Sum size of preceding stream buffers to get position - unsigned totalPreceeding = 0; + // Sum size of preceding stream buffers to get position + unsigned totalPreceding = 0; for ( unsigned i = 0; i < bytestreamNumber; i++ ) { - totalPreceeding += bsbLength[i]; + totalPreceding += bsbLength[i]; } byteCount = bsbLength[bytestreamNumber]; - /// Double check buffer is completely within packet - if ( sizeof( DataPacketHeader ) + 2 * header.bytestreamCount + totalPreceeding + byteCount > + // Double check buffer is completely within packet + if ( ( sizeof( DataPacketHeader ) + 2 * header.bytestreamCount + totalPreceding + byteCount ) > header.packetLogicalLengthMinus1 + 1U ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, - "bytestreamCount=" + toString( header.bytestreamCount ) + " totalPreceeding=" + - toString( totalPreceeding ) + " byteCount=" + toString( byteCount ) + - " packetLogicalLengthMinus1=" + toString( header.packetLogicalLengthMinus1 ) ); + throw E57_EXCEPTION2( ErrorInternal, "bytestreamCount=" + toString( header.bytestreamCount ) + + " totalPreceding=" + toString( totalPreceding ) + + " byteCount=" + toString( byteCount ) + + " packetLogicalLengthMinus1=" + + toString( header.packetLogicalLengthMinus1 ) ); } - /// Return start of buffer - return ( &streamBase[totalPreceeding] ); + // Return start of buffer + return ( &streamBase[totalPreceding] ); } unsigned DataPacket::getBytestreamBufferLength( unsigned bytestreamNumber ) { //??? for now: unsigned byteCount; - (void)getBytestream( bytestreamNumber, byteCount ); + getBytestream( bytestreamNumber, byteCount ); return ( byteCount ); } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void DataPacket::dump( int indent, std::ostream &os ) const { if ( header.packetType != DATA_PACKET ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "packetType=" + toString( header.packetType ) ); + throw E57_EXCEPTION2( ErrorInternal, "packetType=" + toString( header.packetType ) ); } reinterpret_cast( this )->dump( indent, os ); @@ -532,8 +548,8 @@ void DataPacket::dump( int indent, std::ostream &os ) const p += bsbLength[i]; if ( p - reinterpret_cast( this ) > DATA_PACKET_MAX ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, - "size=" + toString( p - reinterpret_cast( this ) ) ); + throw E57_EXCEPTION2( + ErrorInternal, "size=" + toString( p - reinterpret_cast( this ) ) ); } } } @@ -542,153 +558,176 @@ void DataPacket::dump( int indent, std::ostream &os ) const //============================================================================= // IndexPacket -void IndexPacket::verify( unsigned bufferLength, uint64_t totalRecordCount, uint64_t fileSize ) const +void IndexPacket::verify( unsigned bufferLength, uint64_t totalRecordCount, + uint64_t fileSize ) const { - (void)totalRecordCount; (void)fileSize; +#if ( E57_VALIDATION_LEVEL < VALIDATION_DEEP ) + UNUSED( totalRecordCount ); + UNUSED( fileSize ); +#endif + //??? do all packets need versions? how extend without breaking older // checking? need to check // file version#? - /// Verify that packet is correct type - if ( packetType != INDEX_PACKET ) + // Verify that packet is correct type + if ( header.packetType != INDEX_PACKET ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetType=" + toString( packetType ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, + "expected Index; packetType=" + toString( header.packetType ) ); } - /// Check packetLength is at least large enough to hold header - unsigned packetLength = packetLogicalLengthMinus1 + 1; - if ( packetLength < sizeof( *this ) ) + // Check packetLength is at least large enough to hold header + unsigned packetLength = header.packetLogicalLengthMinus1 + 1; + if ( packetLength < sizeof( IndexPacketHeader ) ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetLength=" + toString( packetLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, + "INDEX; less than size of IndexPacketHeader; packetLength=" + + toString( packetLength ) ); } - /// Check packet length is multiple of 4 + // Check packet length is multiple of 4 if ( packetLength % 4 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetLength=" + toString( packetLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "INDEX; length not multiple of 4; packetLength=" + + toString( packetLength ) ); } - /// Make sure there is at least one entry in packet ??? 0 record cvect - /// allowed? - if ( entryCount == 0 ) + // Make sure there is at least one entry in packet ??? 0 record cvect + // allowed? + if ( header.entryCount == 0 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "entryCount=" + toString( entryCount ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, + "INDEX; entryCount=" + toString( header.entryCount ) ); } - /// Have to have <= 2048 entries - if ( entryCount > MAX_ENTRIES ) + // Have to have <= 2048 entries + if ( header.entryCount > MAX_ENTRIES ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "entryCount=" + toString( entryCount ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, + "INDEX; entryCount=" + toString( header.entryCount ) ); } - /// Index level should be <= 5. Because (5+1)* 11 bits = 66 bits, which will - /// cover largest number of chunks possible. - if ( indexLevel > 5 ) + // Index level should be <= 5. Because (5+1)* 11 bits = 66 bits, which will cover largest number + // of chunks possible. + if ( header.indexLevel > 5 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "indexLevel=" + toString( indexLevel ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, + "INDEX; indexLevel=" + toString( header.indexLevel ) ); } - /// Index packets above level 0 must have at least two entries (otherwise no - /// point to existing). - ///??? check that this is in spec - if ( indexLevel > 0 && entryCount < 2 ) + // Index packets above level 0 must have at least two entries (otherwise no point to existing). + //??? check that this is in spec + if ( header.indexLevel > 0 && header.entryCount < 2 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, - "indexLevel=" + toString( indexLevel ) + " entryCount=" + toString( entryCount ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "INDEX; indexLevel=" + toString( header.indexLevel ) + + " entryCount=" + toString( header.entryCount ) ); } - /// If not later version, verify reserved fields are zero. ??? test file - /// version if (version <= E57_FORMAT_MAJOR) { //??? - for ( unsigned i = 0; i < sizeof( reserved1 ); i++ ) + // If not later version, verify reserved fields are zero. ??? test file + // version if (version <= E57_FORMAT_MAJOR) { //??? + for ( unsigned i = 0; i < sizeof( header.reserved1 ); i++ ) { - if ( reserved1[i] != 0 ) + if ( header.reserved1[i] != 0 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "i=" + toString( i ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "i=" + toString( i ) ); } } - /// Check actual packet length is large enough. + // Check actual packet length is large enough. if ( bufferLength > 0 && packetLength > bufferLength ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, - "packetLength=" + toString( packetLength ) + " bufferLength=" + toString( bufferLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "INDEX; packetLength=" + toString( packetLength ) + + " bufferLength=" + toString( bufferLength ) ); } - /// Check if entries will fit in space provided - unsigned neededLength = 16 + 8 * entryCount; - if ( packetLength < neededLength ) + // Check if entries will fit in space provided + const unsigned cNeededLength = + sizeof( IndexPacketHeader ) + sizeof( IndexPacketEntry ) * header.entryCount; + if ( packetLength < cNeededLength ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, - "packetLength=" + toString( packetLength ) + " neededLength=" + toString( neededLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "INDEX; packetLength=" + toString( packetLength ) + + " neededLength=" + toString( cNeededLength ) ); } -#ifdef E57_MAX_DEBUG - /// Verify padding at end is zero. +#if VALIDATE_DEEP + // Verify padding at end is zero. const char *p = reinterpret_cast( this ); - for ( unsigned i = neededLength; i < packetLength; i++ ) + for ( unsigned i = cNeededLength; i < packetLength; i++ ) { if ( p[i] != 0 ) - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "i=" + toString( i ) ); + { + throw E57_EXCEPTION2( ErrorBadCVPacket, "INDEX; padding; i=" + toString( i ) ); + } } - /// Verify records and offsets are in sorted order - for ( unsigned i = 0; i < entryCount; i++ ) + // Verify records and offsets are in sorted order + for ( unsigned i = 0; i < header.entryCount; i++ ) { - /// Check chunkRecordNumber is in bounds + // Check chunkRecordNumber is in bounds if ( totalRecordCount > 0 && entries[i].chunkRecordNumber >= totalRecordCount ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, - "i=" + toString( i ) + " chunkRecordNumber=" + toString( entries[i].chunkRecordNumber ) + + throw E57_EXCEPTION2( ErrorBadCVPacket, + "INDEX; record# in bounds; i=" + toString( i ) + + " chunkRecordNumber=" + toString( entries[i].chunkRecordNumber ) + " totalRecordCount=" + toString( totalRecordCount ) ); } - /// Check record numbers are strictly increasing + // Check record numbers are strictly increasing if ( i > 0 && entries[i - 1].chunkRecordNumber >= entries[i].chunkRecordNumber ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, - "i=" + toString( i ) + - " prevChunkRecordNumber=" + toString( entries[i - 1].chunkRecordNumber ) + - " currentChunkRecordNumber=" + toString( entries[i].chunkRecordNumber ) ); + throw E57_EXCEPTION2( + ErrorBadCVPacket, + "INDEX; record numbers increasing; i=" + toString( i ) + + " prevChunkRecordNumber=" + toString( entries[i - 1].chunkRecordNumber ) + + " currentChunkRecordNumber=" + toString( entries[i].chunkRecordNumber ) ); } - /// Check chunkPhysicalOffset is in bounds + // Check chunkPhysicalOffset is in bounds if ( fileSize > 0 && entries[i].chunkPhysicalOffset >= fileSize ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "i=" + toString( i ) + " chunkPhysicalOffset=" + - toString( entries[i].chunkPhysicalOffset ) + - " fileSize=" + toString( fileSize ) ); + throw E57_EXCEPTION2( + ErrorBadCVPacket, + "INDEX; physical offset in bounds; i=" + toString( i ) + " chunkPhysicalOffset=" + + toString( entries[i].chunkPhysicalOffset ) + " fileSize=" + toString( fileSize ) ); } - /// Check chunk offsets are strictly increasing + // Check chunk offsets are strictly increasing if ( i > 0 && entries[i - 1].chunkPhysicalOffset >= entries[i].chunkPhysicalOffset ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, - "i=" + toString( i ) + - " prevChunkPhysicalOffset=" + toString( entries[i - 1].chunkPhysicalOffset ) + - " currentChunkPhysicalOffset=" + toString( entries[i].chunkPhysicalOffset ) ); + throw E57_EXCEPTION2( + ErrorBadCVPacket, + "INDEX; chunk offsets increasing; i=" + toString( i ) + + " prevChunkPhysicalOffset=" + toString( entries[i - 1].chunkPhysicalOffset ) + + " currentChunkPhysicalOffset=" + toString( entries[i].chunkPhysicalOffset ) ); } } #endif } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void IndexPacket::dump( int indent, std::ostream &os ) const { - os << space( indent ) << "packetType: " << static_cast( packetType ) << std::endl; - os << space( indent ) << "packetFlags: " << static_cast( packetFlags ) << std::endl; - os << space( indent ) << "packetLogicalLengthMinus1: " << packetLogicalLengthMinus1 << std::endl; - os << space( indent ) << "entryCount: " << entryCount << std::endl; - os << space( indent ) << "indexLevel: " << indexLevel << std::endl; + os << space( indent ) + << "packetType: " << static_cast( header.packetType ) << std::endl; + os << space( indent ) + << "packetFlags: " << static_cast( header.packetFlags ) << std::endl; + os << space( indent ) << "packetLogicalLengthMinus1: " << header.packetLogicalLengthMinus1 + << std::endl; + os << space( indent ) << "entryCount: " << header.entryCount << std::endl; + os << space( indent ) << "indexLevel: " << header.indexLevel << std::endl; unsigned i; - for ( i = 0; i < entryCount && i < 10; i++ ) + for ( i = 0; i < header.entryCount && i < 10; i++ ) { os << space( indent ) << "entry[" << i << "]:" << std::endl; - os << space( indent + 4 ) << "chunkRecordNumber: " << entries[i].chunkRecordNumber << std::endl; - os << space( indent + 4 ) << "chunkPhysicalOffset: " << entries[i].chunkPhysicalOffset << std::endl; + os << space( indent + 4 ) << "chunkRecordNumber: " << entries[i].chunkRecordNumber + << std::endl; + os << space( indent + 4 ) << "chunkPhysicalOffset: " << entries[i].chunkPhysicalOffset + << std::endl; } - if ( i < entryCount ) + if ( i < header.entryCount ) { - os << space( indent ) << entryCount - i << "more entries unprinted..." << std::endl; + os << space( indent ) << header.entryCount - i << "more entries unprinted..." << std::endl; } } #endif @@ -698,37 +737,38 @@ void IndexPacket::dump( int indent, std::ostream &os ) const void EmptyPacketHeader::verify( unsigned bufferLength ) const { - /// Verify that packet is correct type + // Verify that packet is correct type if ( packetType != EMPTY_PACKET ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetType=" + toString( packetType ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "packetType=" + toString( packetType ) ); } - /// Check packetLength is at least large enough to hold header + // Check packetLength is at least large enough to hold header unsigned packetLength = packetLogicalLengthMinus1 + 1; if ( packetLength < sizeof( *this ) ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetLength=" + toString( packetLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "packetLength=" + toString( packetLength ) ); } - /// Check packet length is multiple of 4 + // Check packet length is multiple of 4 if ( packetLength % 4 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, "packetLength=" + toString( packetLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "packetLength=" + toString( packetLength ) ); } - /// Check actual packet length is large enough. + // Check actual packet length is large enough. if ( bufferLength > 0 && packetLength > bufferLength ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_PACKET, - "packetLength=" + toString( packetLength ) + " bufferLength=" + toString( bufferLength ) ); + throw E57_EXCEPTION2( ErrorBadCVPacket, "packetLength=" + toString( packetLength ) + + " bufferLength=" + toString( bufferLength ) ); } } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void EmptyPacketHeader::dump( int indent, std::ostream &os ) const { - os << space( indent ) << "packetType: " << static_cast( packetType ) << std::endl; + os << space( indent ) << "packetType: " << static_cast( packetType ) + << std::endl; os << space( indent ) << "packetLogicalLengthMinus1: " << packetLogicalLengthMinus1 << std::endl; } #endif diff --git a/src/3rdParty/libE57Format/src/Packet.h b/src/3rdParty/libE57Format/src/Packet.h index 7d202b2cf1f94..722ce5eb69f57 100644 --- a/src/3rdParty/libE57Format/src/Packet.h +++ b/src/3rdParty/libE57Format/src/Packet.h @@ -37,7 +37,7 @@ namespace e57 class CheckedFile; class PacketLock; - /// Packet types (in a compressed vector section) + // Packet types (in a compressed vector section) enum { INDEX_PACKET = 0, @@ -45,7 +45,7 @@ namespace e57 EMPTY_PACKET, }; - /// maximum size of CompressedVector binary data packet + // Maximum size of CompressedVector binary data packet constexpr int DATA_PACKET_MAX = ( 64 * 1024 ); class PacketReadCache @@ -56,13 +56,14 @@ namespace e57 std::unique_ptr lock( uint64_t packetLogicalOffset, char *&pkt ); //??? pkt could be const -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ); #endif protected: - /// Only PacketLock can unlock the cache friend class PacketLock; + + // Only PacketLock can unlock the cache void unlock( unsigned cacheIndex ); void readPacket( unsigned oldestEntry, uint64_t packetLogicalOffset ); @@ -70,7 +71,7 @@ namespace e57 struct CacheEntry { uint64_t logicalOffset_ = 0; - char buffer_[DATA_PACKET_MAX]; //! No need to init since it's a data buffer + char buffer_[DATA_PACKET_MAX]; // No need to init since it's a data buffer unsigned lastUsed_ = 0; }; @@ -86,13 +87,12 @@ namespace e57 public: ~PacketLock(); - private: - /// Can't be copied or assigned - PacketLock( const PacketLock &plock ); - PacketLock &operator=( const PacketLock &plock ); + PacketLock( const PacketLock &plock ) = delete; + PacketLock &operator=( const PacketLock &plock ) = delete; protected: friend class PacketReadCache; + /// Only PacketReadCache can construct PacketLock( PacketReadCache *cache, unsigned cacheIndex ); @@ -109,9 +109,10 @@ namespace e57 void verify( unsigned bufferLength = 0 ) const; //???use -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const; #endif + const uint8_t packetType = DATA_PACKET; uint8_t packetFlags = 0; @@ -128,7 +129,7 @@ namespace e57 char *getBytestream( unsigned bytestreamNumber, unsigned &byteCount ); unsigned getBytestreamBufferLength( unsigned bytestreamNumber ); -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const; #endif @@ -136,6 +137,6 @@ namespace e57 DataPacketHeader header; - uint8_t payload[PayloadSize]; //! No need to init since it's a data buffer + uint8_t payload[PayloadSize]; // No need to init since it's a data buffer }; } diff --git a/src/3rdParty/libE57Format/src/ReaderImpl.cpp b/src/3rdParty/libE57Format/src/ReaderImpl.cpp index 40814e8125531..23f37cf3516c7 100644 --- a/src/3rdParty/libE57Format/src/ReaderImpl.cpp +++ b/src/3rdParty/libE57Format/src/ReaderImpl.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) 2010 Stan Coleby (scoleby@intelisum.com) * Copyright (c) 2020 PTC Inc. + * Copyright (c) 2022 Andy Maloney * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by @@ -26,13 +27,171 @@ */ #include "ReaderImpl.h" +#include "Common.h" +#include "StringFunctions.h" namespace e57 { + /*! + @brief Reads the data out of a given image node + + @param [in] image 1 of 3 projects or the visual + @param [in] imageType identifies the image format desired. + @param [out] pBuffer pointer the buffer + @param [out] start position in the block to start reading + @param [out] count size of desired chunk or buffer size + + @return number of bytes read + */ + size_t _readImage2DNode( const StructureNode &image, Image2DType imageType, uint8_t *pBuffer, + int64_t start, size_t count ) + { + size_t transferred = 0; + + switch ( imageType ) + { + case ImageNone: + return 0; + + case ImageJPEG: + if ( image.isDefined( "jpegImage" ) ) + { + BlobNode jpegImage( image.get( "jpegImage" ) ); + jpegImage.read( pBuffer, start, count ); + transferred = count; + } + break; + + case ImagePNG: + if ( image.isDefined( "pngImage" ) ) + { + BlobNode pngImage( image.get( "pngImage" ) ); + pngImage.read( pBuffer, start, count ); + transferred = count; + } + break; + + case ImageMaskPNG: + if ( image.isDefined( "imageMask" ) ) + { + BlobNode imageMask( image.get( "imageMask" ) ); + imageMask.read( pBuffer, start, count ); + transferred = count; + } + break; + } - ReaderImpl::ReaderImpl( const ustring &filePath ) : - imf_( filePath, "r" ), root_( imf_.root() ), data3D_( root_.get( "/data3D" ) ), - images2D_( root_.get( "/images2D" ) ) + return transferred; + } + + /*! + @brief This function reads one of the image blobs + + @param [in] image 1 of 3 projects or the visual + @param [out] imageType identifies the image format desired. + @param [out] imageWidth The image width (in pixels). + @param [out] imageHeight The image height (in pixels). + @param [out] imageSize This is the total number of bytes for the image blob. + @param [out] imageMaskType This is E57_PNG_IMAGE_MASK if "imageMask" is defined in the projection + + @return Returns true if successful + */ + static bool _getImage2DNodeSizes( const StructureNode &image, Image2DType &imageType, + int64_t &imageWidth, int64_t &imageHeight, int64_t &imageSize, + Image2DType &imageMaskType ) + { + imageWidth = 0; + imageHeight = 0; + imageSize = 0; + imageType = ImageNone; + imageMaskType = ImageNone; + + if ( image.isDefined( "imageWidth" ) ) + { + imageWidth = IntegerNode( image.get( "imageWidth" ) ).value(); + } + else + { + return false; + } + + if ( image.isDefined( "imageHeight" ) ) + { + imageHeight = IntegerNode( image.get( "imageHeight" ) ).value(); + } + else + { + return false; + } + + if ( image.isDefined( "jpegImage" ) ) + { + imageSize = BlobNode( image.get( "jpegImage" ) ).byteCount(); + imageType = ImageJPEG; + } + else if ( image.isDefined( "pngImage" ) ) + { + imageSize = BlobNode( image.get( "pngImage" ) ).byteCount(); + imageType = ImagePNG; + } + + if ( image.isDefined( "imageMask" ) ) + { + if ( imageType == ImageNone ) + { + imageSize = BlobNode( image.get( "imageMask" ) ).byteCount(); + imageType = ImageMaskPNG; + } + + imageMaskType = ImageMaskPNG; + } + + return true; + } + + /// Possibly get min/max from the colour node itself instead of the colorLimits. + void _readColourRanges( const std::string &protoName, const StructureNode &proto, + double &colourMin, double &colourMax ) + { + // IF the colorLimits are not set + // AND our colour node is + // THEN get our min/max from the colour node itself. + if ( ( colourMax == 0.0 ) && proto.isDefined( protoName ) ) + { + const auto colourProto = proto.get( protoName ); + + if ( colourProto.type() == TypeInteger ) + { + const IntegerNode integerColour( colourProto ); + + colourMin = static_cast( integerColour.minimum() ); + colourMax = static_cast( integerColour.maximum() ); + } + else if ( colourProto.type() == TypeScaledInteger ) + { + const ScaledIntegerNode scaledColour( colourProto ); + const double scale = scaledColour.scale(); + const double offset = scaledColour.offset(); + const int64_t minimum = scaledColour.minimum(); + const int64_t maximum = scaledColour.maximum(); + + colourMin = static_cast( minimum ) * scale + offset; + colourMax = static_cast( maximum ) * scale + offset; + } + else if ( colourProto.type() == TypeFloat ) + { + const FloatNode floatColour( colourProto ); + + colourMin = static_cast( floatColour.minimum() ); + colourMax = static_cast( floatColour.maximum() ); + } + } + } + + ReaderImpl::ReaderImpl( const ustring &filePath, const ReaderOptions &options ) : + imf_( filePath, "r", options.checksumPolicy ), root_( imf_.root() ), + data3D_( root_.get( "/data3D" ) ), + images2D_( root_.isDefined( "/images2D" ) ? root_.get( "/images2D" ) : VectorNode( imf_ ) ) { } @@ -44,13 +203,11 @@ namespace e57 } } - // This function returns true if the file is open bool ReaderImpl::IsOpen() const { return imf_.isOpen(); } - // This function closes the file bool ReaderImpl::Close() { if ( !IsOpen() ) @@ -62,7 +219,7 @@ namespace e57 return true; } - // This function returns the file header information + // Returns the file header information in fileHeader bool ReaderImpl::GetE57Root( E57Root &fileHeader ) const { if ( !IsOpen() ) @@ -73,8 +230,10 @@ namespace e57 fileHeader = {}; fileHeader.formatName = StringNode( root_.get( "formatName" ) ).value(); - fileHeader.versionMajor = (uint32_t)IntegerNode( root_.get( "versionMajor" ) ).value(); - fileHeader.versionMinor = (uint32_t)IntegerNode( root_.get( "versionMinor" ) ).value(); + fileHeader.versionMajor = + static_cast( IntegerNode( root_.get( "versionMajor" ) ).value() ); + fileHeader.versionMinor = + static_cast( IntegerNode( root_.get( "versionMinor" ) ).value() ); fileHeader.guid = StringNode( root_.get( "guid" ) ).value(); if ( root_.isDefined( "e57LibraryVersion" ) ) { @@ -88,10 +247,16 @@ namespace e57 if ( root_.isDefined( "creationDateTime" ) ) { - StructureNode creationDateTime( root_.get( "creationDateTime" ) ); - fileHeader.creationDateTime.dateTimeValue = FloatNode( creationDateTime.get( "dateTimeValue" ) ).value(); - fileHeader.creationDateTime.isAtomicClockReferenced = - (int32_t)IntegerNode( creationDateTime.get( "isAtomicClockReferenced" ) ).value(); + const StructureNode creationDateTime( root_.get( "creationDateTime" ) ); + + fileHeader.creationDateTime.dateTimeValue = + FloatNode( creationDateTime.get( "dateTimeValue" ) ).value(); + + if ( creationDateTime.isDefined( "isAtomicClockReferenced" ) ) + { + fileHeader.creationDateTime.isAtomicClockReferenced = static_cast( + IntegerNode( creationDateTime.get( "isAtomicClockReferenced" ) ).value() ); + } } fileHeader.data3DSize = data3D_.childCount(); @@ -105,7 +270,7 @@ namespace e57 return images2D_.childCount(); } - // This function returns the Image2Ds header and positions the cursor + // Returns the Image2Ds header and positions the cursor bool ReaderImpl::ReadImage2D( int64_t imageIndex, Image2D &image2DHeader ) const { if ( !IsOpen() ) @@ -119,7 +284,7 @@ namespace e57 image2DHeader = {}; - StructureNode image( images2D_.get( imageIndex ) ); + const StructureNode image( images2D_.get( imageIndex ) ); image2DHeader.guid = StringNode( image.get( "guid" ) ).value(); @@ -148,25 +313,33 @@ namespace e57 if ( image.isDefined( "associatedData3DGuid" ) ) { - image2DHeader.associatedData3DGuid = StringNode( image.get( "associatedData3DGuid" ) ).value(); + image2DHeader.associatedData3DGuid = + StringNode( image.get( "associatedData3DGuid" ) ).value(); } if ( image.isDefined( "acquisitionDateTime" ) ) { - StructureNode acquisitionDateTime( image.get( "acquisitionDateTime" ) ); + const StructureNode acquisitionDateTime( image.get( "acquisitionDateTime" ) ); + image2DHeader.acquisitionDateTime.dateTimeValue = FloatNode( acquisitionDateTime.get( "dateTimeValue" ) ).value(); - image2DHeader.acquisitionDateTime.isAtomicClockReferenced = - (int32_t)IntegerNode( acquisitionDateTime.get( "isAtomicClockReferenced" ) ).value(); + + if ( acquisitionDateTime.isDefined( "isAtomicClockReferenced" ) ) + { + image2DHeader.acquisitionDateTime.isAtomicClockReferenced = static_cast( + IntegerNode( acquisitionDateTime.get( "isAtomicClockReferenced" ) ).value() ); + } } // Get pose structure for scan. if ( image.isDefined( "pose" ) ) { - StructureNode pose( image.get( "pose" ) ); + const StructureNode pose( image.get( "pose" ) ); + if ( pose.isDefined( "rotation" ) ) { - StructureNode rotation( pose.get( "rotation" ) ); + const StructureNode rotation( pose.get( "rotation" ) ); + image2DHeader.pose.rotation.w = FloatNode( rotation.get( "w" ) ).value(); image2DHeader.pose.rotation.x = FloatNode( rotation.get( "x" ) ).value(); image2DHeader.pose.rotation.y = FloatNode( rotation.get( "y" ) ).value(); @@ -174,7 +347,8 @@ namespace e57 } if ( pose.isDefined( "translation" ) ) { - StructureNode translation( pose.get( "translation" ) ); + const StructureNode translation( pose.get( "translation" ) ); + image2DHeader.pose.translation.x = FloatNode( translation.get( "x" ) ).value(); image2DHeader.pose.translation.y = FloatNode( translation.get( "y" ) ).value(); image2DHeader.pose.translation.z = FloatNode( translation.get( "z" ) ).value(); @@ -183,7 +357,8 @@ namespace e57 if ( image.isDefined( "visualReferenceRepresentation" ) ) { - StructureNode visualReferenceRepresentation( image.get( "visualReferenceRepresentation" ) ); + const StructureNode visualReferenceRepresentation( + image.get( "visualReferenceRepresentation" ) ); if ( visualReferenceRepresentation.isDefined( "jpegImage" ) ) { @@ -201,15 +376,15 @@ namespace e57 BlobNode( visualReferenceRepresentation.get( "imageMask" ) ).byteCount(); } - image2DHeader.visualReferenceRepresentation.imageHeight = - (int32_t)IntegerNode( visualReferenceRepresentation.get( "imageHeight" ) ).value(); - image2DHeader.visualReferenceRepresentation.imageWidth = - (int32_t)IntegerNode( visualReferenceRepresentation.get( "imageWidth" ) ).value(); + image2DHeader.visualReferenceRepresentation.imageHeight = static_cast( + IntegerNode( visualReferenceRepresentation.get( "imageHeight" ) ).value() ); + image2DHeader.visualReferenceRepresentation.imageWidth = static_cast( + IntegerNode( visualReferenceRepresentation.get( "imageWidth" ) ).value() ); } if ( image.isDefined( "pinholeRepresentation" ) ) { - StructureNode pinholeRepresentation( image.get( "pinholeRepresentation" ) ); + const StructureNode pinholeRepresentation( image.get( "pinholeRepresentation" ) ); if ( pinholeRepresentation.isDefined( "jpegImage" ) ) { @@ -229,10 +404,10 @@ namespace e57 image2DHeader.pinholeRepresentation.focalLength = FloatNode( pinholeRepresentation.get( "focalLength" ) ).value(); - image2DHeader.pinholeRepresentation.imageHeight = - (int32_t)IntegerNode( pinholeRepresentation.get( "imageHeight" ) ).value(); - image2DHeader.pinholeRepresentation.imageWidth = - (int32_t)IntegerNode( pinholeRepresentation.get( "imageWidth" ) ).value(); + image2DHeader.pinholeRepresentation.imageHeight = static_cast( + IntegerNode( pinholeRepresentation.get( "imageHeight" ) ).value() ); + image2DHeader.pinholeRepresentation.imageWidth = static_cast( + IntegerNode( pinholeRepresentation.get( "imageWidth" ) ).value() ); image2DHeader.pinholeRepresentation.pixelHeight = FloatNode( pinholeRepresentation.get( "pixelHeight" ) ).value(); @@ -245,7 +420,7 @@ namespace e57 } else if ( image.isDefined( "sphericalRepresentation" ) ) { - StructureNode sphericalRepresentation( image.get( "sphericalRepresentation" ) ); + const StructureNode sphericalRepresentation( image.get( "sphericalRepresentation" ) ); if ( sphericalRepresentation.isDefined( "jpegImage" ) ) { @@ -263,10 +438,10 @@ namespace e57 BlobNode( sphericalRepresentation.get( "imageMask" ) ).byteCount(); } - image2DHeader.sphericalRepresentation.imageHeight = - (int32_t)IntegerNode( sphericalRepresentation.get( "imageHeight" ) ).value(); - image2DHeader.sphericalRepresentation.imageWidth = - (int32_t)IntegerNode( sphericalRepresentation.get( "imageWidth" ) ).value(); + image2DHeader.sphericalRepresentation.imageHeight = static_cast( + IntegerNode( sphericalRepresentation.get( "imageHeight" ) ).value() ); + image2DHeader.sphericalRepresentation.imageWidth = static_cast( + IntegerNode( sphericalRepresentation.get( "imageWidth" ) ).value() ); image2DHeader.sphericalRepresentation.pixelHeight = FloatNode( sphericalRepresentation.get( "pixelHeight" ) ).value(); @@ -275,7 +450,7 @@ namespace e57 } else if ( image.isDefined( "cylindricalRepresentation" ) ) { - StructureNode cylindricalRepresentation( image.get( "cylindricalRepresentation" ) ); + const StructureNode cylindricalRepresentation( image.get( "cylindricalRepresentation" ) ); if ( cylindricalRepresentation.isDefined( "jpegImage" ) ) { @@ -293,10 +468,10 @@ namespace e57 BlobNode( cylindricalRepresentation.get( "imageMask" ) ).byteCount(); } - image2DHeader.cylindricalRepresentation.imageHeight = - (int32_t)IntegerNode( cylindricalRepresentation.get( "imageHeight" ) ).value(); - image2DHeader.cylindricalRepresentation.imageWidth = - (int32_t)IntegerNode( cylindricalRepresentation.get( "imageWidth" ) ).value(); + image2DHeader.cylindricalRepresentation.imageHeight = static_cast( + IntegerNode( cylindricalRepresentation.get( "imageHeight" ) ).value() ); + image2DHeader.cylindricalRepresentation.imageWidth = static_cast( + IntegerNode( cylindricalRepresentation.get( "imageWidth" ) ).value() ); image2DHeader.cylindricalRepresentation.pixelHeight = FloatNode( cylindricalRepresentation.get( "pixelHeight" ) ).value(); @@ -311,252 +486,167 @@ namespace e57 return true; } - // This function reads one of the image blobs - int64_t ReaderImpl::ReadImage2DNode( StructureNode image, Image2DType imageType, void *pBuffer, int64_t start, - int64_t count ) const - { - int64_t transferred = 0; - switch ( imageType ) - { - case E57_NO_IMAGE: - { - return 0; - } - case E57_JPEG_IMAGE: - { - if ( image.isDefined( "jpegImage" ) ) - { - BlobNode jpegImage( image.get( "jpegImage" ) ); - jpegImage.read( (uint8_t *)pBuffer, start, (size_t)count ); - transferred = count; - } - break; - } - case E57_PNG_IMAGE: - { - if ( image.isDefined( "pngImage" ) ) - { - BlobNode pngImage( image.get( "pngImage" ) ); - pngImage.read( (uint8_t *)pBuffer, start, (size_t)count ); - transferred = count; - } - break; - } - case E57_PNG_IMAGE_MASK: - { - if ( image.isDefined( "imageMask" ) ) - { - BlobNode imageMask( image.get( "imageMask" ) ); - imageMask.read( (uint8_t *)pBuffer, start, (size_t)count ); - transferred = count; - } - break; - } - } - return transferred; - } - - // This function reads one of the image blobs - bool ReaderImpl::GetImage2DNodeSizes( StructureNode image, Image2DType &imageType, int64_t &imageWidth, - int64_t &imageHeight, int64_t &imageSize, Image2DType &imageMaskType ) const - { - imageWidth = 0; - imageHeight = 0; - imageSize = 0; - imageType = E57_NO_IMAGE; - imageMaskType = E57_NO_IMAGE; - - if ( image.isDefined( "imageWidth" ) ) - { - imageWidth = IntegerNode( image.get( "imageWidth" ) ).value(); - } - else - { - return false; - } - - if ( image.isDefined( "imageHeight" ) ) - { - imageHeight = IntegerNode( image.get( "imageHeight" ) ).value(); - } - else - { - return false; - } - - if ( image.isDefined( "jpegImage" ) ) - { - imageSize = BlobNode( image.get( "jpegImage" ) ).byteCount(); - imageType = E57_JPEG_IMAGE; - } - else if ( image.isDefined( "pngImage" ) ) - { - imageSize = BlobNode( image.get( "pngImage" ) ).byteCount(); - imageType = E57_PNG_IMAGE; - } - - if ( image.isDefined( "imageMask" ) ) - { - if ( imageType == E57_NO_IMAGE ) - { - imageSize = BlobNode( image.get( "imageMask" ) ).byteCount(); - imageType = E57_PNG_IMAGE_MASK; - } - imageMaskType = E57_PNG_IMAGE_MASK; - } - return true; - } - - // This function returns the image sizes - bool ReaderImpl::GetImage2DSizes( int64_t imageIndex, Image2DProjection &imageProjection, Image2DType &imageType, - int64_t &imageWidth, int64_t &imageHeight, int64_t &imageSize, - Image2DType &imageMaskType, Image2DType &imageVisualType ) const + // Returns the image sizes + bool ReaderImpl::GetImage2DSizes( int64_t imageIndex, Image2DProjection &imageProjection, + Image2DType &imageType, int64_t &imageWidth, + int64_t &imageHeight, int64_t &imageSize, + Image2DType &imageMaskType, + Image2DType &imageVisualType ) const { if ( ( imageIndex < 0 ) || ( imageIndex >= images2D_.childCount() ) ) { return false; } - imageProjection = E57_NO_PROJECTION; - imageType = E57_NO_IMAGE; - imageMaskType = E57_NO_IMAGE; - imageVisualType = E57_NO_IMAGE; + imageProjection = ProjectionNone; + imageType = ImageNone; + imageMaskType = ImageNone; + imageVisualType = ImageNone; - bool ret = false; - StructureNode image( images2D_.get( imageIndex ) ); + const StructureNode image( images2D_.get( imageIndex ) ); if ( image.isDefined( "visualReferenceRepresentation" ) ) { - imageProjection = E57_VISUAL; - StructureNode visualReferenceRepresentation( image.get( "visualReferenceRepresentation" ) ); - ret = GetImage2DNodeSizes( visualReferenceRepresentation, imageType, imageWidth, imageHeight, imageSize, - imageMaskType ); + const StructureNode visualReferenceRepresentation( + image.get( "visualReferenceRepresentation" ) ); + + bool ret = _getImage2DNodeSizes( visualReferenceRepresentation, imageType, imageWidth, + imageHeight, imageSize, imageMaskType ); + imageProjection = ProjectionVisual; imageVisualType = imageType; + + return ret; } if ( image.isDefined( "pinholeRepresentation" ) ) { - imageProjection = E57_PINHOLE; - StructureNode pinholeRepresentation( image.get( "pinholeRepresentation" ) ); - ret = - GetImage2DNodeSizes( pinholeRepresentation, imageType, imageWidth, imageHeight, imageSize, imageMaskType ); + const StructureNode pinholeRepresentation( image.get( "pinholeRepresentation" ) ); + + imageProjection = ProjectionPinhole; + + return _getImage2DNodeSizes( pinholeRepresentation, imageType, imageWidth, imageHeight, + imageSize, imageMaskType ); } - else if ( image.isDefined( "sphericalRepresentation" ) ) + + if ( image.isDefined( "sphericalRepresentation" ) ) { - imageProjection = E57_SPHERICAL; - StructureNode sphericalRepresentation( image.get( "sphericalRepresentation" ) ); - ret = GetImage2DNodeSizes( sphericalRepresentation, imageType, imageWidth, imageHeight, imageSize, - imageMaskType ); + const StructureNode sphericalRepresentation( image.get( "sphericalRepresentation" ) ); + + imageProjection = ProjectionSpherical; + + return _getImage2DNodeSizes( sphericalRepresentation, imageType, imageWidth, imageHeight, + imageSize, imageMaskType ); } - else if ( image.isDefined( "cylindricalRepresentation" ) ) + + if ( image.isDefined( "cylindricalRepresentation" ) ) { - imageProjection = E57_CYLINDRICAL; - StructureNode cylindricalRepresentation( image.get( "cylindricalRepresentation" ) ); - ret = GetImage2DNodeSizes( cylindricalRepresentation, imageType, imageWidth, imageHeight, imageSize, - imageMaskType ); + const StructureNode cylindricalRepresentation( image.get( "cylindricalRepresentation" ) ); + + imageProjection = ProjectionCylindrical; + + return _getImage2DNodeSizes( cylindricalRepresentation, imageType, imageWidth, imageHeight, + imageSize, imageMaskType ); } - return ret; + return false; } - // This function reads the block - int64_t ReaderImpl::ReadImage2DData( int64_t imageIndex, Image2DProjection imageProjection, Image2DType imageType, - void *pBuffer, int64_t start, int64_t count ) const + // Reads the image data block + size_t ReaderImpl::ReadImage2DData( int64_t imageIndex, Image2DProjection imageProjection, + Image2DType imageType, uint8_t *pBuffer, int64_t start, + size_t count ) const { if ( ( imageIndex < 0 ) || ( imageIndex >= images2D_.childCount() ) ) { return 0; } - int64_t transferred = 0; - StructureNode image( images2D_.get( imageIndex ) ); + const StructureNode image( images2D_.get( imageIndex ) ); switch ( imageProjection ) { - case E57_NO_PROJECTION: + case ProjectionNone: return 0; - case E57_VISUAL: + + case ProjectionVisual: if ( image.isDefined( "visualReferenceRepresentation" ) ) { - StructureNode visualReferenceRepresentation( image.get( "visualReferenceRepresentation" ) ); - transferred = ReadImage2DNode( visualReferenceRepresentation, imageType, pBuffer, start, count ); + const StructureNode visualReferenceRepresentation( + image.get( "visualReferenceRepresentation" ) ); + + return _readImage2DNode( visualReferenceRepresentation, imageType, pBuffer, start, + count ); } break; - case E57_PINHOLE: + case ProjectionPinhole: if ( image.isDefined( "pinholeRepresentation" ) ) { - StructureNode pinholeRepresentation( image.get( "pinholeRepresentation" ) ); - transferred = ReadImage2DNode( pinholeRepresentation, imageType, pBuffer, start, count ); + const StructureNode pinholeRepresentation( image.get( "pinholeRepresentation" ) ); + + return _readImage2DNode( pinholeRepresentation, imageType, pBuffer, start, count ); } break; - case E57_SPHERICAL: + case ProjectionSpherical: if ( image.isDefined( "sphericalRepresentation" ) ) { - StructureNode sphericalRepresentation( image.get( "sphericalRepresentation" ) ); - transferred = ReadImage2DNode( sphericalRepresentation, imageType, pBuffer, start, count ); + const StructureNode sphericalRepresentation( + image.get( "sphericalRepresentation" ) ); + + return _readImage2DNode( sphericalRepresentation, imageType, pBuffer, start, count ); } break; - case E57_CYLINDRICAL: + case ProjectionCylindrical: if ( image.isDefined( "cylindricalRepresentation" ) ) { - StructureNode cylindricalRepresentation( image.get( "cylindricalRepresentation" ) ); - transferred = ReadImage2DNode( cylindricalRepresentation, imageType, pBuffer, start, count ); + const StructureNode cylindricalRepresentation( + image.get( "cylindricalRepresentation" ) ); + + return _readImage2DNode( cylindricalRepresentation, imageType, pBuffer, start, + count ); } break; } - return transferred; - } - - int64_t ReaderImpl::GetData3DCount() const - { - return data3D_.childCount(); - } - - StructureNode ReaderImpl::GetRawE57Root() const - { - return root_; - } - - VectorNode ReaderImpl::GetRawData3D() const - { - return data3D_; - } - - VectorNode ReaderImpl::GetRawImages2D() const - { - return images2D_; - } - - ImageFile ReaderImpl::GetRawIMF() const - { - return imf_; + return 0; } bool ReaderImpl::ReadData3D( int64_t dataIndex, Data3D &data3DHeader ) const { - if ( !IsOpen() ) - { - return false; - } - if ( ( dataIndex < 0 ) || ( dataIndex >= data3D_.childCount() ) ) + if ( !IsOpen() || ( dataIndex < 0 ) || ( dataIndex >= data3D_.childCount() ) ) { return false; } data3DHeader = {}; - StructureNode scan( data3D_.get( dataIndex ) ); + const StructureNode scan( data3D_.get( dataIndex ) ); CompressedVectorNode points( scan.get( "points" ) ); - - data3DHeader.pointsSize = points.childCount(); - StructureNode proto( points.prototype() ); + const StructureNode proto( points.prototype() ); data3DHeader.guid = StringNode( scan.get( "guid" ) ).value(); +#ifdef E57_32_BIT + // If we exceed the size_t max, only process the max (4,294,967,295 points). + if ( points.childCount() > static_cast( std::numeric_limits::max() ) ) + { + data3DHeader.pointCount = std::numeric_limits::max(); + + std::cout << "Warning (32-bit): Point count (" << points.childCount() + << ") exceeds storage capacity (" << std::numeric_limits::max() + << "). Dropping " << points.childCount() - std::numeric_limits::max() + << " points from scan." << std::endl; + } + else + { + data3DHeader.pointCount = static_cast( points.childCount() ); + } +#else + data3DHeader.pointCount = points.childCount(); +#endif + if ( scan.isDefined( "name" ) ) { data3DHeader.name = StringNode( scan.get( "name" ) ).value(); @@ -568,20 +658,22 @@ namespace e57 if ( scan.isDefined( "originalGuids" ) ) { - VectorNode originalGuids( scan.get( "originalGuids" ) ); + const VectorNode originalGuids( scan.get( "originalGuids" ) ); + if ( originalGuids.childCount() > 0 ) { data3DHeader.originalGuids.clear(); - int i; - for ( i = 0; i < originalGuids.childCount(); i++ ) + + for ( int64_t i = 0; i < originalGuids.childCount(); ++i ) { - ustring str = StringNode( originalGuids.get( i ) ).value(); + const ustring str = StringNode( originalGuids.get( i ) ).value(); + data3DHeader.originalGuids.push_back( str ); } } } - // Get various sensor and version strings to scan. + // Get various sensor and version strings from scan. if ( scan.isDefined( "sensorVendor" ) ) { data3DHeader.sensorVendor = StringNode( scan.get( "sensorVendor" ) ).value(); @@ -596,34 +688,41 @@ namespace e57 } if ( scan.isDefined( "sensorHardwareVersion" ) ) { - data3DHeader.sensorHardwareVersion = StringNode( scan.get( "sensorHardwareVersion" ) ).value(); + data3DHeader.sensorHardwareVersion = + StringNode( scan.get( "sensorHardwareVersion" ) ).value(); } if ( scan.isDefined( "sensorSoftwareVersion" ) ) { - data3DHeader.sensorSoftwareVersion = StringNode( scan.get( "sensorSoftwareVersion" ) ).value(); + data3DHeader.sensorSoftwareVersion = + StringNode( scan.get( "sensorSoftwareVersion" ) ).value(); } if ( scan.isDefined( "sensorFirmwareVersion" ) ) { - data3DHeader.sensorFirmwareVersion = StringNode( scan.get( "sensorFirmwareVersion" ) ).value(); + data3DHeader.sensorFirmwareVersion = + StringNode( scan.get( "sensorFirmwareVersion" ) ).value(); } - // Get temp/humidity to scan. + // Get temp/humidity from scan. if ( scan.isDefined( "temperature" ) ) { - data3DHeader.temperature = (float)FloatNode( scan.get( "temperature" ) ).value(); + data3DHeader.temperature = + static_cast( FloatNode( scan.get( "temperature" ) ).value() ); } if ( scan.isDefined( "relativeHumidity" ) ) { - data3DHeader.relativeHumidity = (float)FloatNode( scan.get( "relativeHumidity" ) ).value(); + data3DHeader.relativeHumidity = + static_cast( FloatNode( scan.get( "relativeHumidity" ) ).value() ); } if ( scan.isDefined( "atmosphericPressure" ) ) { - data3DHeader.atmosphericPressure = (float)FloatNode( scan.get( "atmosphericPressure" ) ).value(); + data3DHeader.atmosphericPressure = + static_cast( FloatNode( scan.get( "atmosphericPressure" ) ).value() ); } if ( scan.isDefined( "indexBounds" ) ) { - StructureNode ibox( scan.get( "indexBounds" ) ); + const StructureNode ibox( scan.get( "indexBounds" ) ); + if ( ibox.isDefined( "rowMaximum" ) ) { data3DHeader.indexBounds.rowMinimum = IntegerNode( ibox.get( "rowMinimum" ) ).value(); @@ -631,30 +730,36 @@ namespace e57 } if ( ibox.isDefined( "columnMaximum" ) ) { - data3DHeader.indexBounds.columnMinimum = IntegerNode( ibox.get( "columnMinimum" ) ).value(); - data3DHeader.indexBounds.columnMaximum = IntegerNode( ibox.get( "columnMaximum" ) ).value(); + data3DHeader.indexBounds.columnMinimum = + IntegerNode( ibox.get( "columnMinimum" ) ).value(); + data3DHeader.indexBounds.columnMaximum = + IntegerNode( ibox.get( "columnMaximum" ) ).value(); } if ( ibox.isDefined( "returnMaximum" ) ) { - data3DHeader.indexBounds.returnMinimum = IntegerNode( ibox.get( "returnMinimum" ) ).value(); - data3DHeader.indexBounds.returnMaximum = IntegerNode( ibox.get( "returnMaximum" ) ).value(); + data3DHeader.indexBounds.returnMinimum = + IntegerNode( ibox.get( "returnMinimum" ) ).value(); + data3DHeader.indexBounds.returnMaximum = + IntegerNode( ibox.get( "returnMaximum" ) ).value(); } } if ( scan.isDefined( "pointGroupingSchemes" ) ) { - StructureNode pointGroupingSchemes( scan.get( "pointGroupingSchemes" ) ); + const StructureNode pointGroupingSchemes( scan.get( "pointGroupingSchemes" ) ); + if ( pointGroupingSchemes.isDefined( "groupingByLine" ) ) { - StructureNode groupingByLine( pointGroupingSchemes.get( "groupingByLine" ) ); + const StructureNode groupingByLine( pointGroupingSchemes.get( "groupingByLine" ) ); data3DHeader.pointGroupingSchemes.groupingByLine.idElementName = StringNode( groupingByLine.get( "idElementName" ) ).value(); - CompressedVectorNode groups( groupingByLine.get( "groups" ) ); + const CompressedVectorNode groups( groupingByLine.get( "groups" ) ); + const StructureNode lineGroupRecord( groups.prototype() ); + data3DHeader.pointGroupingSchemes.groupingByLine.groupsSize = groups.childCount(); - StructureNode lineGroupRecord( groups.prototype() ); if ( lineGroupRecord.isDefined( "pointCount" ) ) { data3DHeader.pointGroupingSchemes.groupingByLine.pointCountSize = @@ -663,20 +768,27 @@ namespace e57 } } - // Get Cartesian bounding box to scan. + // Get Cartesian bounding box from scan. if ( scan.isDefined( "cartesianBounds" ) ) { - StructureNode bbox( scan.get( "cartesianBounds" ) ); - if ( bbox.get( "xMinimum" ).type() == E57_SCALED_INTEGER ) + const StructureNode bbox( scan.get( "cartesianBounds" ) ); + + if ( bbox.get( "xMinimum" ).type() == TypeScaledInteger ) { - data3DHeader.cartesianBounds.xMinimum = (double)ScaledIntegerNode( bbox.get( "xMinimum" ) ).scaledValue(); - data3DHeader.cartesianBounds.xMaximum = (double)ScaledIntegerNode( bbox.get( "xMaximum" ) ).scaledValue(); - data3DHeader.cartesianBounds.yMinimum = (double)ScaledIntegerNode( bbox.get( "yMinimum" ) ).scaledValue(); - data3DHeader.cartesianBounds.yMaximum = (double)ScaledIntegerNode( bbox.get( "yMaximum" ) ).scaledValue(); - data3DHeader.cartesianBounds.zMinimum = (double)ScaledIntegerNode( bbox.get( "zMinimum" ) ).scaledValue(); - data3DHeader.cartesianBounds.zMaximum = (double)ScaledIntegerNode( bbox.get( "zMaximum" ) ).scaledValue(); + data3DHeader.cartesianBounds.xMinimum = + ScaledIntegerNode( bbox.get( "xMinimum" ) ).scaledValue(); + data3DHeader.cartesianBounds.xMaximum = + ScaledIntegerNode( bbox.get( "xMaximum" ) ).scaledValue(); + data3DHeader.cartesianBounds.yMinimum = + ScaledIntegerNode( bbox.get( "yMinimum" ) ).scaledValue(); + data3DHeader.cartesianBounds.yMaximum = + ScaledIntegerNode( bbox.get( "yMaximum" ) ).scaledValue(); + data3DHeader.cartesianBounds.zMinimum = + ScaledIntegerNode( bbox.get( "zMinimum" ) ).scaledValue(); + data3DHeader.cartesianBounds.zMaximum = + ScaledIntegerNode( bbox.get( "zMaximum" ) ).scaledValue(); } - else if ( bbox.get( "xMinimum" ).type() == E57_FLOAT ) + else if ( bbox.get( "xMinimum" ).type() == TypeFloat ) { data3DHeader.cartesianBounds.xMinimum = FloatNode( bbox.get( "xMinimum" ) ).value(); data3DHeader.cartesianBounds.xMaximum = FloatNode( bbox.get( "xMaximum" ) ).value(); @@ -689,160 +801,292 @@ namespace e57 if ( scan.isDefined( "sphericalBounds" ) ) { - StructureNode sbox( scan.get( "sphericalBounds" ) ); - if ( sbox.get( "rangeMinimum" ).type() == E57_SCALED_INTEGER ) + const StructureNode sbox( scan.get( "sphericalBounds" ) ); + + if ( sbox.get( "rangeMinimum" ).type() == TypeScaledInteger ) { data3DHeader.sphericalBounds.rangeMinimum = - (double)ScaledIntegerNode( sbox.get( "rangeMinimum" ) ).scaledValue(); + ScaledIntegerNode( sbox.get( "rangeMinimum" ) ).scaledValue(); data3DHeader.sphericalBounds.rangeMaximum = - (double)ScaledIntegerNode( sbox.get( "rangeMaximum" ) ).scaledValue(); + ScaledIntegerNode( sbox.get( "rangeMaximum" ) ).scaledValue(); } - else if ( sbox.get( "rangeMinimum" ).type() == E57_FLOAT ) + else if ( sbox.get( "rangeMinimum" ).type() == TypeFloat ) { - data3DHeader.sphericalBounds.rangeMinimum = FloatNode( sbox.get( "rangeMinimum" ) ).value(); - data3DHeader.sphericalBounds.rangeMaximum = FloatNode( sbox.get( "rangeMaximum" ) ).value(); + data3DHeader.sphericalBounds.rangeMinimum = + FloatNode( sbox.get( "rangeMinimum" ) ).value(); + data3DHeader.sphericalBounds.rangeMaximum = + FloatNode( sbox.get( "rangeMaximum" ) ).value(); } - if ( sbox.get( "elevationMinimum" ).type() == E57_SCALED_INTEGER ) + if ( sbox.get( "elevationMinimum" ).type() == TypeScaledInteger ) { data3DHeader.sphericalBounds.elevationMinimum = - (double)ScaledIntegerNode( sbox.get( "elevationMinimum" ) ).scaledValue(); + ScaledIntegerNode( sbox.get( "elevationMinimum" ) ).scaledValue(); data3DHeader.sphericalBounds.elevationMaximum = - (double)ScaledIntegerNode( sbox.get( "elevationMaximum" ) ).scaledValue(); + ScaledIntegerNode( sbox.get( "elevationMaximum" ) ).scaledValue(); } - else if ( sbox.get( "elevationMinimum" ).type() == E57_FLOAT ) + else if ( sbox.get( "elevationMinimum" ).type() == TypeFloat ) { - data3DHeader.sphericalBounds.elevationMinimum = FloatNode( sbox.get( "elevationMinimum" ) ).value(); - data3DHeader.sphericalBounds.elevationMaximum = FloatNode( sbox.get( "elevationMaximum" ) ).value(); + data3DHeader.sphericalBounds.elevationMinimum = + FloatNode( sbox.get( "elevationMinimum" ) ).value(); + data3DHeader.sphericalBounds.elevationMaximum = + FloatNode( sbox.get( "elevationMaximum" ) ).value(); } - if ( sbox.get( "azimuthStart" ).type() == E57_SCALED_INTEGER ) + if ( sbox.get( "azimuthStart" ).type() == TypeScaledInteger ) { data3DHeader.sphericalBounds.azimuthStart = - (double)ScaledIntegerNode( sbox.get( "azimuthStart" ) ).scaledValue(); + ScaledIntegerNode( sbox.get( "azimuthStart" ) ).scaledValue(); data3DHeader.sphericalBounds.azimuthEnd = - (double)ScaledIntegerNode( sbox.get( "azimuthEnd" ) ).scaledValue(); + ScaledIntegerNode( sbox.get( "azimuthEnd" ) ).scaledValue(); } - else if ( sbox.get( "azimuthStart" ).type() == E57_FLOAT ) + else if ( sbox.get( "azimuthStart" ).type() == TypeFloat ) { - data3DHeader.sphericalBounds.azimuthStart = FloatNode( sbox.get( "azimuthStart" ) ).value(); + data3DHeader.sphericalBounds.azimuthStart = + FloatNode( sbox.get( "azimuthStart" ) ).value(); data3DHeader.sphericalBounds.azimuthEnd = FloatNode( sbox.get( "azimuthEnd" ) ).value(); } } - // Get pose structure for scan. + // Get pose structure from scan. if ( scan.isDefined( "pose" ) ) { - StructureNode pose( scan.get( "pose" ) ); + const StructureNode pose( scan.get( "pose" ) ); + if ( pose.isDefined( "rotation" ) ) { - StructureNode rotation( pose.get( "rotation" ) ); + const StructureNode rotation( pose.get( "rotation" ) ); + data3DHeader.pose.rotation.w = FloatNode( rotation.get( "w" ) ).value(); data3DHeader.pose.rotation.x = FloatNode( rotation.get( "x" ) ).value(); data3DHeader.pose.rotation.y = FloatNode( rotation.get( "y" ) ).value(); data3DHeader.pose.rotation.z = FloatNode( rotation.get( "z" ) ).value(); } + if ( pose.isDefined( "translation" ) ) { - StructureNode translation( pose.get( "translation" ) ); + const StructureNode translation( pose.get( "translation" ) ); + data3DHeader.pose.translation.x = FloatNode( translation.get( "x" ) ).value(); data3DHeader.pose.translation.y = FloatNode( translation.get( "y" ) ).value(); data3DHeader.pose.translation.z = FloatNode( translation.get( "z" ) ).value(); } } - // Get start/stop acquisition times to scan. + // Get start/stop acquisition times from scan. if ( scan.isDefined( "acquisitionStart" ) ) { - StructureNode acquisitionStart( scan.get( "acquisitionStart" ) ); - data3DHeader.acquisitionStart.dateTimeValue = FloatNode( acquisitionStart.get( "dateTimeValue" ) ).value(); - data3DHeader.acquisitionStart.isAtomicClockReferenced = - (int32_t)IntegerNode( acquisitionStart.get( "isAtomicClockReferenced" ) ).value(); + const StructureNode acquisitionStart( scan.get( "acquisitionStart" ) ); + + data3DHeader.acquisitionStart.dateTimeValue = + FloatNode( acquisitionStart.get( "dateTimeValue" ) ).value(); + + if ( acquisitionStart.isDefined( "isAtomicClockReferenced" ) ) + { + data3DHeader.acquisitionStart.isAtomicClockReferenced = static_cast( + IntegerNode( acquisitionStart.get( "isAtomicClockReferenced" ) ).value() ); + } } if ( scan.isDefined( "acquisitionEnd" ) ) { - StructureNode acquisitionEnd( scan.get( "acquisitionEnd" ) ); - data3DHeader.acquisitionEnd.dateTimeValue = FloatNode( acquisitionEnd.get( "dateTimeValue" ) ).value(); - data3DHeader.acquisitionEnd.isAtomicClockReferenced = - (int32_t)IntegerNode( acquisitionEnd.get( "isAtomicClockReferenced" ) ).value(); + const StructureNode acquisitionEnd( scan.get( "acquisitionEnd" ) ); + + data3DHeader.acquisitionEnd.dateTimeValue = + FloatNode( acquisitionEnd.get( "dateTimeValue" ) ).value(); + + if ( acquisitionEnd.isDefined( "isAtomicClockReferenced" ) ) + { + data3DHeader.acquisitionEnd.isAtomicClockReferenced = static_cast( + IntegerNode( acquisitionEnd.get( "isAtomicClockReferenced" ) ).value() ); + } } - // Get a prototype of datatypes that will be stored in points record. + // Get a prototype of datatypes that are stored in points record. data3DHeader.pointFields.cartesianXField = proto.isDefined( "cartesianX" ); data3DHeader.pointFields.cartesianYField = proto.isDefined( "cartesianY" ); data3DHeader.pointFields.cartesianZField = proto.isDefined( "cartesianZ" ); - data3DHeader.pointFields.cartesianInvalidStateField = proto.isDefined( "cartesianInvalidState" ); + data3DHeader.pointFields.cartesianInvalidStateField = + proto.isDefined( "cartesianInvalidState" ); - data3DHeader.pointFields.pointRangeScaledInteger = E57_NOT_SCALED_USE_FLOAT; // FloatNode - data3DHeader.pointFields.pointRangeMinimum = 0.; - data3DHeader.pointFields.pointRangeMaximum = 0.; + data3DHeader.pointFields.pointRangeMinimum = 0.0; + data3DHeader.pointFields.pointRangeMaximum = 0.0; if ( proto.isDefined( "cartesianX" ) ) { - if ( proto.get( "cartesianX" ).type() == E57_SCALED_INTEGER ) - { - double scale = ScaledIntegerNode( proto.get( "cartesianX" ) ).scale(); - double offset = ScaledIntegerNode( proto.get( "cartesianX" ) ).offset(); - int64_t minimum = ScaledIntegerNode( proto.get( "cartesianX" ) ).minimum(); - int64_t maximum = ScaledIntegerNode( proto.get( "cartesianX" ) ).maximum(); - data3DHeader.pointFields.pointRangeMinimum = (double)minimum * scale + offset; - data3DHeader.pointFields.pointRangeMaximum = (double)maximum * scale + offset; - data3DHeader.pointFields.pointRangeScaledInteger = scale; - } - else if ( proto.get( "cartesianX" ).type() == E57_FLOAT ) + const auto cartesianXProto = proto.get( "cartesianX" ); + + switch ( cartesianXProto.type() ) { - data3DHeader.pointFields.pointRangeMinimum = FloatNode( proto.get( "cartesianX" ) ).minimum(); - data3DHeader.pointFields.pointRangeMaximum = FloatNode( proto.get( "cartesianX" ) ).maximum(); - data3DHeader.pointFields.pointRangeScaledInteger = E57_NOT_SCALED_USE_FLOAT; + case TypeInteger: + { + // Should be a warning that we don't handle this type, but we don't have a mechanism + // for warnings. + break; + } + + case TypeScaledInteger: + { + const ScaledIntegerNode scaledCartesianX( cartesianXProto ); + const double scale = scaledCartesianX.scale(); + const double offset = scaledCartesianX.offset(); + const int64_t minimum = scaledCartesianX.minimum(); + const int64_t maximum = scaledCartesianX.maximum(); + + data3DHeader.pointFields.pointRangeMinimum = + static_cast( minimum ) * scale + offset; + data3DHeader.pointFields.pointRangeMaximum = + static_cast( maximum ) * scale + offset; + + data3DHeader.pointFields.pointRangeNodeType = NumericalNodeType::ScaledInteger; + data3DHeader.pointFields.pointRangeScale = scale; + + break; + } + + case TypeFloat: + { + const FloatNode floatCartesianX( cartesianXProto ); + + data3DHeader.pointFields.pointRangeMinimum = floatCartesianX.minimum(); + data3DHeader.pointFields.pointRangeMaximum = floatCartesianX.maximum(); + + if ( floatCartesianX.precision() == PrecisionSingle ) + { + data3DHeader.pointFields.pointRangeNodeType = NumericalNodeType::Float; + } + else + { + data3DHeader.pointFields.pointRangeNodeType = NumericalNodeType::Double; + } + + break; + } + + default: + throw E57_EXCEPTION2( ErrorInvalidNodeType, + "invalid node type reading cartesianX field: " + + toString( cartesianXProto.type() ) ); + break; } } else if ( proto.isDefined( "sphericalRange" ) ) { - if ( proto.get( "sphericalRange" ).type() == E57_SCALED_INTEGER ) - { - double scale = ScaledIntegerNode( proto.get( "sphericalRange" ) ).scale(); - double offset = ScaledIntegerNode( proto.get( "sphericalRange" ) ).offset(); - int64_t minimum = ScaledIntegerNode( proto.get( "sphericalRange" ) ).minimum(); - int64_t maximum = ScaledIntegerNode( proto.get( "sphericalRange" ) ).maximum(); - data3DHeader.pointFields.pointRangeMinimum = (double)minimum * scale + offset; - data3DHeader.pointFields.pointRangeMaximum = (double)maximum * scale + offset; - data3DHeader.pointFields.pointRangeScaledInteger = scale; - } - else if ( proto.get( "sphericalRange" ).type() == E57_FLOAT ) + const auto sphericalRangeProto = proto.get( "sphericalRange" ); + + switch ( sphericalRangeProto.type() ) { - data3DHeader.pointFields.pointRangeMinimum = FloatNode( proto.get( "sphericalRange" ) ).minimum(); - data3DHeader.pointFields.pointRangeMaximum = FloatNode( proto.get( "sphericalRange" ) ).maximum(); - data3DHeader.pointFields.pointRangeScaledInteger = E57_NOT_SCALED_USE_FLOAT; + case TypeInteger: + { + // Should be a warning that we don't handle this type, but we don't have a mechanism + // for warnings. + break; + } + + case TypeScaledInteger: + { + const ScaledIntegerNode scaledSphericalRange( sphericalRangeProto ); + const double scale = scaledSphericalRange.scale(); + const double offset = scaledSphericalRange.offset(); + const int64_t minimum = scaledSphericalRange.minimum(); + const int64_t maximum = scaledSphericalRange.maximum(); + + data3DHeader.pointFields.pointRangeMinimum = + static_cast( minimum ) * scale + offset; + data3DHeader.pointFields.pointRangeMaximum = + static_cast( maximum ) * scale + offset; + + data3DHeader.pointFields.pointRangeNodeType = NumericalNodeType::ScaledInteger; + data3DHeader.pointFields.pointRangeScale = scale; + + break; + } + + case TypeFloat: + { + const FloatNode floatSphericalRange( sphericalRangeProto ); + + data3DHeader.pointFields.pointRangeMinimum = floatSphericalRange.minimum(); + data3DHeader.pointFields.pointRangeMaximum = floatSphericalRange.maximum(); + + if ( floatSphericalRange.precision() == PrecisionSingle ) + { + data3DHeader.pointFields.pointRangeNodeType = NumericalNodeType::Float; + } + else + { + data3DHeader.pointFields.pointRangeNodeType = NumericalNodeType::Double; + } + + break; + } + + default: + throw E57_EXCEPTION2( ErrorInvalidNodeType, + "invalid node type reading sphericalRange field: " + + toString( sphericalRangeProto.type() ) ); + break; } } data3DHeader.pointFields.sphericalRangeField = proto.isDefined( "sphericalRange" ); data3DHeader.pointFields.sphericalAzimuthField = proto.isDefined( "sphericalAzimuth" ); data3DHeader.pointFields.sphericalElevationField = proto.isDefined( "sphericalElevation" ); - data3DHeader.pointFields.sphericalInvalidStateField = proto.isDefined( "sphericalInvalidState" ); + data3DHeader.pointFields.sphericalInvalidStateField = + proto.isDefined( "sphericalInvalidState" ); - data3DHeader.pointFields.angleScaledInteger = E57_NOT_SCALED_USE_FLOAT; // FloatNode - data3DHeader.pointFields.angleMinimum = 0.; - data3DHeader.pointFields.angleMaximum = 0.; + data3DHeader.pointFields.angleMinimum = 0.0; + data3DHeader.pointFields.angleMaximum = 0.0; if ( proto.isDefined( "sphericalAzimuth" ) ) { - if ( proto.get( "sphericalAzimuth" ).type() == E57_SCALED_INTEGER ) - { - double scale = ScaledIntegerNode( proto.get( "sphericalAzimuth" ) ).scale(); - double offset = ScaledIntegerNode( proto.get( "sphericalAzimuth" ) ).offset(); - int64_t minimum = ScaledIntegerNode( proto.get( "sphericalAzimuth" ) ).minimum(); - int64_t maximum = ScaledIntegerNode( proto.get( "sphericalAzimuth" ) ).maximum(); - data3DHeader.pointFields.angleMinimum = (double)minimum * scale + offset; - data3DHeader.pointFields.angleMaximum = (double)maximum * scale + offset; - data3DHeader.pointFields.angleScaledInteger = scale; - } - else if ( proto.get( "sphericalAzimuth" ).type() == E57_FLOAT ) + const auto sphericalAzimuthProto = proto.get( "sphericalAzimuth" ); + + switch ( sphericalAzimuthProto.type() ) { - data3DHeader.pointFields.angleMinimum = FloatNode( proto.get( "sphericalAzimuth" ) ).minimum(); - data3DHeader.pointFields.angleMaximum = FloatNode( proto.get( "sphericalAzimuth" ) ).maximum(); - data3DHeader.pointFields.angleScaledInteger = E57_NOT_SCALED_USE_FLOAT; + case TypeScaledInteger: + { + const ScaledIntegerNode scaledSphericalAzimuth( sphericalAzimuthProto ); + const double scale = scaledSphericalAzimuth.scale(); + const double offset = scaledSphericalAzimuth.offset(); + const int64_t minimum = scaledSphericalAzimuth.minimum(); + const int64_t maximum = scaledSphericalAzimuth.maximum(); + + data3DHeader.pointFields.angleMinimum = + static_cast( minimum ) * scale + offset; + data3DHeader.pointFields.angleMaximum = + static_cast( maximum ) * scale + offset; + + data3DHeader.pointFields.angleNodeType = NumericalNodeType::ScaledInteger; + data3DHeader.pointFields.angleScale = scale; + + break; + } + + case TypeFloat: + { + const FloatNode floatSphericalAzimuth( sphericalAzimuthProto ); + + data3DHeader.pointFields.angleMinimum = floatSphericalAzimuth.minimum(); + data3DHeader.pointFields.angleMaximum = floatSphericalAzimuth.maximum(); + + if ( floatSphericalAzimuth.precision() == PrecisionSingle ) + { + data3DHeader.pointFields.angleNodeType = NumericalNodeType::Float; + } + else + { + data3DHeader.pointFields.angleNodeType = NumericalNodeType::Double; + } + + break; + } + + default: + throw E57_EXCEPTION2( ErrorInvalidNodeType, + "invalid node type reading sphericalAzimuth field: " + + toString( sphericalAzimuthProto.type() ) ); + break; } } @@ -853,12 +1097,14 @@ namespace e57 if ( proto.isDefined( "rowIndex" ) ) { - data3DHeader.pointFields.rowIndexMaximum = (uint32_t)IntegerNode( proto.get( "rowIndex" ) ).maximum(); + data3DHeader.pointFields.rowIndexMaximum = + static_cast( IntegerNode( proto.get( "rowIndex" ) ).maximum() ); } if ( proto.isDefined( "columnIndex" ) ) { - data3DHeader.pointFields.columnIndexMaximum = (uint32_t)IntegerNode( proto.get( "columnIndex" ) ).maximum(); + data3DHeader.pointFields.columnIndexMaximum = + static_cast( IntegerNode( proto.get( "columnIndex" ) ).maximum() ); } data3DHeader.pointFields.returnIndexField = proto.isDefined( "returnIndex" ); @@ -867,105 +1113,186 @@ namespace e57 if ( proto.isDefined( "returnIndex" ) ) { - data3DHeader.pointFields.returnMaximum = (uint8_t)IntegerNode( proto.get( "returnIndex" ) ).maximum(); + data3DHeader.pointFields.returnMaximum = + static_cast( IntegerNode( proto.get( "returnIndex" ) ).maximum() ); } data3DHeader.pointFields.timeStampField = proto.isDefined( "timeStamp" ); data3DHeader.pointFields.isTimeStampInvalidField = proto.isDefined( "isTimeStampInvalid" ); - data3DHeader.pointFields.timeMaximum = 0.; - data3DHeader.pointFields.timeMinimum = 0.; - data3DHeader.pointFields.timeScaledInteger = E57_NOT_SCALED_USE_FLOAT; + data3DHeader.pointFields.timeMaximum = 0.0; + data3DHeader.pointFields.timeMinimum = 0.0; if ( proto.isDefined( "timeStamp" ) ) { - if ( proto.get( "timeStamp" ).type() == E57_INTEGER ) - { - data3DHeader.pointFields.timeMaximum = (double)IntegerNode( proto.get( "timeStamp" ) ).maximum(); - data3DHeader.pointFields.timeMinimum = (double)IntegerNode( proto.get( "timeStamp" ) ).minimum(); - data3DHeader.pointFields.timeScaledInteger = E57_NOT_SCALED_USE_FLOAT; - } - else if ( proto.get( "timeStamp" ).type() == E57_SCALED_INTEGER ) - { - double scale = ScaledIntegerNode( proto.get( "timeStamp" ) ).scale(); - double offset = ScaledIntegerNode( proto.get( "timeStamp" ) ).offset(); - int64_t minimum = ScaledIntegerNode( proto.get( "timeStamp" ) ).minimum(); - int64_t maximum = ScaledIntegerNode( proto.get( "timeStamp" ) ).maximum(); - data3DHeader.pointFields.timeMinimum = (double)minimum * scale + offset; - data3DHeader.pointFields.timeMaximum = (double)maximum * scale + offset; - data3DHeader.pointFields.timeScaledInteger = scale; - } - else if ( proto.get( "timeStamp" ).type() == E57_FLOAT ) + const auto timeStampProto = proto.get( "timeStamp" ); + + switch ( timeStampProto.type() ) { - data3DHeader.pointFields.timeMinimum = FloatNode( proto.get( "timeStamp" ) ).minimum(); - data3DHeader.pointFields.timeMaximum = FloatNode( proto.get( "timeStamp" ) ).maximum(); - data3DHeader.pointFields.timeScaledInteger = E57_NOT_SCALED_USE_FLOAT; + case TypeInteger: + { + const IntegerNode integerTimeStamp( timeStampProto ); + + data3DHeader.pointFields.timeMaximum = + static_cast( integerTimeStamp.maximum() ); + data3DHeader.pointFields.timeMinimum = + static_cast( integerTimeStamp.minimum() ); + + data3DHeader.pointFields.timeNodeType = NumericalNodeType::Integer; + + break; + } + + case TypeScaledInteger: + { + const ScaledIntegerNode scaledTimeStamp( timeStampProto ); + + const double scale = scaledTimeStamp.scale(); + const double offset = scaledTimeStamp.offset(); + const int64_t minimum = scaledTimeStamp.minimum(); + const int64_t maximum = scaledTimeStamp.maximum(); + + data3DHeader.pointFields.timeMinimum = + static_cast( minimum ) * scale + offset; + data3DHeader.pointFields.timeMaximum = + static_cast( maximum ) * scale + offset; + + data3DHeader.pointFields.timeNodeType = NumericalNodeType::ScaledInteger; + data3DHeader.pointFields.timeScale = scale; + + break; + } + + case TypeFloat: + { + const FloatNode floatTimeStamp( timeStampProto ); + + data3DHeader.pointFields.timeMinimum = floatTimeStamp.minimum(); + data3DHeader.pointFields.timeMaximum = floatTimeStamp.maximum(); + + if ( floatTimeStamp.precision() == PrecisionSingle ) + { + data3DHeader.pointFields.timeNodeType = NumericalNodeType::Float; + } + else + { + data3DHeader.pointFields.timeNodeType = NumericalNodeType::Double; + } + + break; + } + + default: + throw E57_EXCEPTION2( ErrorInvalidNodeType, + "invalid node type reading timeStamp field: " + + toString( timeStampProto.type() ) ); + break; } } data3DHeader.pointFields.intensityField = proto.isDefined( "intensity" ); data3DHeader.pointFields.isIntensityInvalidField = proto.isDefined( "isIntensityInvalid" ); - data3DHeader.intensityLimits.intensityMinimum = 0.; - data3DHeader.intensityLimits.intensityMaximum = 0.; - data3DHeader.pointFields.intensityScaledInteger = E57_NOT_SCALED_USE_FLOAT; + data3DHeader.intensityLimits.intensityMinimum = 0.0; + data3DHeader.intensityLimits.intensityMaximum = 0.0; if ( scan.isDefined( "intensityLimits" ) ) { - StructureNode intbox( scan.get( "intensityLimits" ) ); - if ( intbox.get( "intensityMaximum" ).type() == E57_SCALED_INTEGER ) + const StructureNode intbox( scan.get( "intensityLimits" ) ); + const auto intensityMaximumProto = intbox.get( "intensityMaximum" ); + const auto intensityMinimumProto = intbox.get( "intensityMinimum" ); + + if ( intensityMaximumProto.type() == TypeScaledInteger ) { data3DHeader.intensityLimits.intensityMaximum = - (double)ScaledIntegerNode( intbox.get( "intensityMaximum" ) ).scaledValue(); + ScaledIntegerNode( intensityMaximumProto ).scaledValue(); data3DHeader.intensityLimits.intensityMinimum = - (double)ScaledIntegerNode( intbox.get( "intensityMinimum" ) ).scaledValue(); + ScaledIntegerNode( intensityMinimumProto ).scaledValue(); } - else if ( intbox.get( "intensityMaximum" ).type() == E57_FLOAT ) + else if ( intensityMaximumProto.type() == TypeFloat ) { - data3DHeader.intensityLimits.intensityMaximum = FloatNode( intbox.get( "intensityMaximum" ) ).value(); - data3DHeader.intensityLimits.intensityMinimum = FloatNode( intbox.get( "intensityMinimum" ) ).value(); + data3DHeader.intensityLimits.intensityMaximum = + FloatNode( intensityMaximumProto ).value(); + data3DHeader.intensityLimits.intensityMinimum = + FloatNode( intensityMinimumProto ).value(); } - else if ( intbox.get( "intensityMaximum" ).type() == E57_INTEGER ) + else if ( intensityMaximumProto.type() == TypeInteger ) { data3DHeader.intensityLimits.intensityMaximum = - (double)IntegerNode( intbox.get( "intensityMaximum" ) ).value(); + static_cast( IntegerNode( intensityMaximumProto ).value() ); data3DHeader.intensityLimits.intensityMinimum = - (double)IntegerNode( intbox.get( "intensityMinimum" ) ).value(); + static_cast( IntegerNode( intensityMinimumProto ).value() ); } } + if ( proto.isDefined( "intensity" ) ) { - if ( proto.get( "intensity" ).type() == E57_INTEGER ) + const auto intensityProto = proto.get( "intensity" ); + + switch ( intensityProto.type() ) { - if ( data3DHeader.intensityLimits.intensityMaximum == 0. ) + case TypeInteger: { - data3DHeader.intensityLimits.intensityMinimum = - (double)IntegerNode( proto.get( "intensity" ) ).minimum(); - data3DHeader.intensityLimits.intensityMaximum = - (double)IntegerNode( proto.get( "intensity" ) ).maximum(); + const IntegerNode integerIntensity( intensityProto ); + + if ( data3DHeader.intensityLimits.intensityMaximum == 0.0 ) + { + data3DHeader.intensityLimits.intensityMinimum = + static_cast( integerIntensity.minimum() ); + data3DHeader.intensityLimits.intensityMaximum = + static_cast( integerIntensity.maximum() ); + } + + data3DHeader.pointFields.intensityNodeType = NumericalNodeType::Integer; + + break; } - data3DHeader.pointFields.intensityScaledInteger = E57_NOT_SCALED_USE_INTEGER; - } - else if ( proto.get( "intensity" ).type() == E57_SCALED_INTEGER ) - { - double scale = ScaledIntegerNode( proto.get( "intensity" ) ).scale(); - double offset = ScaledIntegerNode( proto.get( "intensity" ) ).offset(); - if ( data3DHeader.intensityLimits.intensityMaximum == 0. ) + case TypeScaledInteger: { - int64_t minimum = ScaledIntegerNode( proto.get( "intensity" ) ).minimum(); - int64_t maximum = ScaledIntegerNode( proto.get( "intensity" ) ).maximum(); - data3DHeader.intensityLimits.intensityMinimum = (double)minimum * scale + offset; - data3DHeader.intensityLimits.intensityMaximum = (double)maximum * scale + offset; + const ScaledIntegerNode scaledIntensity( intensityProto ); + double scale = scaledIntensity.scale(); + double offset = scaledIntensity.offset(); + + if ( data3DHeader.intensityLimits.intensityMaximum == 0.0 ) + { + const int64_t minimum = scaledIntensity.minimum(); + const int64_t maximum = scaledIntensity.maximum(); + + data3DHeader.intensityLimits.intensityMinimum = + static_cast( minimum ) * scale + offset; + data3DHeader.intensityLimits.intensityMaximum = + static_cast( maximum ) * scale + offset; + } + + data3DHeader.pointFields.intensityNodeType = NumericalNodeType::ScaledInteger; + data3DHeader.pointFields.intensityScale = scale; + + break; } - data3DHeader.pointFields.intensityScaledInteger = scale; - } - else if ( proto.get( "intensity" ).type() == E57_FLOAT ) - { - if ( data3DHeader.intensityLimits.intensityMaximum == 0. ) + + case TypeFloat: { - data3DHeader.intensityLimits.intensityMinimum = FloatNode( proto.get( "intensity" ) ).minimum(); - data3DHeader.intensityLimits.intensityMaximum = FloatNode( proto.get( "intensity" ) ).maximum(); + const FloatNode floatIntensity( intensityProto ); + + data3DHeader.intensityLimits.intensityMinimum = floatIntensity.minimum(); + data3DHeader.intensityLimits.intensityMaximum = floatIntensity.maximum(); + + if ( floatIntensity.precision() == PrecisionSingle ) + { + data3DHeader.pointFields.intensityNodeType = NumericalNodeType::Float; + } + else + { + data3DHeader.pointFields.intensityNodeType = NumericalNodeType::Double; + } + + break; } - data3DHeader.pointFields.intensityScaledInteger = E57_NOT_SCALED_USE_FLOAT; + + default: + throw E57_EXCEPTION2( ErrorInvalidNodeType, + "invalid node type reading intensity field: " + + toString( intensityProto.type() ) ); + break; } } @@ -974,163 +1301,111 @@ namespace e57 data3DHeader.pointFields.colorBlueField = proto.isDefined( "colorBlue" ); data3DHeader.pointFields.isColorInvalidField = proto.isDefined( "isColorInvalid" ); - data3DHeader.colorLimits.colorRedMinimum = 0.; - data3DHeader.colorLimits.colorRedMaximum = 0.; - data3DHeader.colorLimits.colorGreenMinimum = 0.; - data3DHeader.colorLimits.colorGreenMaximum = 0.; - data3DHeader.colorLimits.colorBlueMinimum = 0.; - data3DHeader.colorLimits.colorBlueMaximum = 0.; + data3DHeader.colorLimits.colorRedMinimum = 0.0; + data3DHeader.colorLimits.colorRedMaximum = 0.0; + data3DHeader.colorLimits.colorGreenMinimum = 0.0; + data3DHeader.colorLimits.colorGreenMaximum = 0.0; + data3DHeader.colorLimits.colorBlueMinimum = 0.0; + data3DHeader.colorLimits.colorBlueMaximum = 0.0; if ( scan.isDefined( "colorLimits" ) ) { - StructureNode colorbox( scan.get( "colorLimits" ) ); - if ( colorbox.get( "colorRedMaximum" ).type() == E57_SCALED_INTEGER ) + const StructureNode colorbox( scan.get( "colorLimits" ) ); + + if ( colorbox.get( "colorRedMaximum" ).type() == TypeScaledInteger ) { data3DHeader.colorLimits.colorRedMaximum = - (double)ScaledIntegerNode( colorbox.get( "colorRedMaximum" ) ).scaledValue(); + ScaledIntegerNode( colorbox.get( "colorRedMaximum" ) ).scaledValue(); data3DHeader.colorLimits.colorRedMinimum = - (double)ScaledIntegerNode( colorbox.get( "colorRedMinimum" ) ).scaledValue(); + ScaledIntegerNode( colorbox.get( "colorRedMinimum" ) ).scaledValue(); data3DHeader.colorLimits.colorGreenMaximum = - (double)ScaledIntegerNode( colorbox.get( "colorGreenMaximum" ) ).scaledValue(); + ScaledIntegerNode( colorbox.get( "colorGreenMaximum" ) ).scaledValue(); data3DHeader.colorLimits.colorGreenMinimum = - (double)ScaledIntegerNode( colorbox.get( "colorGreenMinimum" ) ).scaledValue(); + ScaledIntegerNode( colorbox.get( "colorGreenMinimum" ) ).scaledValue(); data3DHeader.colorLimits.colorBlueMaximum = - (double)ScaledIntegerNode( colorbox.get( "colorBlueMaximum" ) ).scaledValue(); + ScaledIntegerNode( colorbox.get( "colorBlueMaximum" ) ).scaledValue(); data3DHeader.colorLimits.colorBlueMinimum = - (double)ScaledIntegerNode( colorbox.get( "colorBlueMinimum" ) ).scaledValue(); + ScaledIntegerNode( colorbox.get( "colorBlueMinimum" ) ).scaledValue(); } - else if ( colorbox.get( "colorRedMaximum" ).type() == E57_FLOAT ) + else if ( colorbox.get( "colorRedMaximum" ).type() == TypeFloat ) { - data3DHeader.colorLimits.colorRedMaximum = FloatNode( colorbox.get( "colorRedMaximum" ) ).value(); - data3DHeader.colorLimits.colorRedMinimum = FloatNode( colorbox.get( "colorRedMinimum" ) ).value(); - data3DHeader.colorLimits.colorGreenMaximum = FloatNode( colorbox.get( "colorGreenMaximum" ) ).value(); - data3DHeader.colorLimits.colorGreenMinimum = FloatNode( colorbox.get( "colorGreenMinimum" ) ).value(); - data3DHeader.colorLimits.colorBlueMaximum = FloatNode( colorbox.get( "colorBlueMaximum" ) ).value(); - data3DHeader.colorLimits.colorBlueMinimum = FloatNode( colorbox.get( "colorBlueMinimum" ) ).value(); + data3DHeader.colorLimits.colorRedMaximum = + FloatNode( colorbox.get( "colorRedMaximum" ) ).value(); + data3DHeader.colorLimits.colorRedMinimum = + FloatNode( colorbox.get( "colorRedMinimum" ) ).value(); + data3DHeader.colorLimits.colorGreenMaximum = + FloatNode( colorbox.get( "colorGreenMaximum" ) ).value(); + data3DHeader.colorLimits.colorGreenMinimum = + FloatNode( colorbox.get( "colorGreenMinimum" ) ).value(); + data3DHeader.colorLimits.colorBlueMaximum = + FloatNode( colorbox.get( "colorBlueMaximum" ) ).value(); + data3DHeader.colorLimits.colorBlueMinimum = + FloatNode( colorbox.get( "colorBlueMinimum" ) ).value(); } - else if ( colorbox.get( "colorRedMaximum" ).type() == E57_INTEGER ) + else if ( colorbox.get( "colorRedMaximum" ).type() == TypeInteger ) { - data3DHeader.colorLimits.colorRedMaximum = (double)IntegerNode( colorbox.get( "colorRedMaximum" ) ).value(); - data3DHeader.colorLimits.colorRedMinimum = (double)IntegerNode( colorbox.get( "colorRedMinimum" ) ).value(); + data3DHeader.colorLimits.colorRedMaximum = + static_cast( IntegerNode( colorbox.get( "colorRedMaximum" ) ).value() ); + data3DHeader.colorLimits.colorRedMinimum = + static_cast( IntegerNode( colorbox.get( "colorRedMinimum" ) ).value() ); data3DHeader.colorLimits.colorGreenMaximum = - (double)IntegerNode( colorbox.get( "colorGreenMaximum" ) ).value(); + static_cast( IntegerNode( colorbox.get( "colorGreenMaximum" ) ).value() ); data3DHeader.colorLimits.colorGreenMinimum = - (double)IntegerNode( colorbox.get( "colorGreenMinimum" ) ).value(); + static_cast( IntegerNode( colorbox.get( "colorGreenMinimum" ) ).value() ); data3DHeader.colorLimits.colorBlueMaximum = - (double)IntegerNode( colorbox.get( "colorBlueMaximum" ) ).value(); + static_cast( IntegerNode( colorbox.get( "colorBlueMaximum" ) ).value() ); data3DHeader.colorLimits.colorBlueMinimum = - (double)IntegerNode( colorbox.get( "colorBlueMinimum" ) ).value(); + static_cast( IntegerNode( colorbox.get( "colorBlueMinimum" ) ).value() ); } } - if ( ( data3DHeader.colorLimits.colorRedMaximum == 0. ) && proto.isDefined( "colorRed" ) ) - { - if ( proto.get( "colorRed" ).type() == E57_INTEGER ) - { - data3DHeader.colorLimits.colorRedMinimum = (uint16_t)IntegerNode( proto.get( "colorRed" ) ).minimum(); - data3DHeader.colorLimits.colorRedMaximum = (uint16_t)IntegerNode( proto.get( "colorRed" ) ).maximum(); - } - else if ( proto.get( "colorRed" ).type() == E57_FLOAT ) - { - data3DHeader.colorLimits.colorRedMinimum = (uint16_t)FloatNode( proto.get( "colorRed" ) ).minimum(); - data3DHeader.colorLimits.colorRedMaximum = (uint16_t)FloatNode( proto.get( "colorRed" ) ).maximum(); - } - else if ( proto.get( "colorRed" ).type() == E57_SCALED_INTEGER ) - { - double scale = ScaledIntegerNode( proto.get( "colorRed" ) ).scale(); - double offset = ScaledIntegerNode( proto.get( "colorRed" ) ).offset(); - int64_t minimum = ScaledIntegerNode( proto.get( "colorRed" ) ).minimum(); - int64_t maximum = ScaledIntegerNode( proto.get( "colorRed" ) ).maximum(); - data3DHeader.colorLimits.colorRedMinimum = (uint16_t)minimum * scale + offset; - data3DHeader.colorLimits.colorRedMaximum = (uint16_t)maximum * scale + offset; - } - } - if ( ( data3DHeader.colorLimits.colorGreenMaximum == 0. ) && proto.isDefined( "colorGreen" ) ) - { - if ( proto.get( "colorGreen" ).type() == E57_INTEGER ) - { - data3DHeader.colorLimits.colorGreenMinimum = (uint16_t)IntegerNode( proto.get( "colorGreen" ) ).minimum(); - data3DHeader.colorLimits.colorGreenMaximum = (uint16_t)IntegerNode( proto.get( "colorGreen" ) ).maximum(); - } - else if ( proto.get( "colorGreen" ).type() == E57_FLOAT ) - { - data3DHeader.colorLimits.colorGreenMinimum = (uint16_t)FloatNode( proto.get( "colorGreen" ) ).minimum(); - data3DHeader.colorLimits.colorGreenMaximum = (uint16_t)FloatNode( proto.get( "colorGreen" ) ).maximum(); - } - else if ( proto.get( "colorGreen" ).type() == E57_SCALED_INTEGER ) - { - double scale = ScaledIntegerNode( proto.get( "colorGreen" ) ).scale(); - double offset = ScaledIntegerNode( proto.get( "colorGreen" ) ).offset(); - int64_t minimum = ScaledIntegerNode( proto.get( "colorGreen" ) ).minimum(); - int64_t maximum = ScaledIntegerNode( proto.get( "colorGreen" ) ).maximum(); - data3DHeader.colorLimits.colorGreenMinimum = (uint16_t)minimum * scale + offset; - data3DHeader.colorLimits.colorGreenMaximum = (uint16_t)maximum * scale + offset; - } - } - if ( ( data3DHeader.colorLimits.colorBlueMaximum == 0. ) && proto.isDefined( "colorBlue" ) ) - { - if ( proto.get( "colorBlue" ).type() == E57_INTEGER ) - { - data3DHeader.colorLimits.colorBlueMinimum = (uint16_t)IntegerNode( proto.get( "colorBlue" ) ).minimum(); - data3DHeader.colorLimits.colorBlueMaximum = (uint16_t)IntegerNode( proto.get( "colorBlue" ) ).maximum(); - } - else if ( proto.get( "colorBlue" ).type() == E57_FLOAT ) - { - data3DHeader.colorLimits.colorBlueMinimum = (uint16_t)FloatNode( proto.get( "colorBlue" ) ).minimum(); - data3DHeader.colorLimits.colorBlueMaximum = (uint16_t)FloatNode( proto.get( "colorBlue" ) ).maximum(); - } - else if ( proto.get( "colorBlue" ).type() == E57_SCALED_INTEGER ) - { - double scale = ScaledIntegerNode( proto.get( "colorBlue" ) ).scale(); - double offset = ScaledIntegerNode( proto.get( "colorBlue" ) ).offset(); - int64_t minimum = ScaledIntegerNode( proto.get( "colorBlue" ) ).minimum(); - int64_t maximum = ScaledIntegerNode( proto.get( "colorBlue" ) ).maximum(); - data3DHeader.colorLimits.colorRedMinimum = (uint16_t)minimum * scale + offset; - data3DHeader.colorLimits.colorRedMaximum = (uint16_t)maximum * scale + offset; - } - } + _readColourRanges( "colorRed", proto, data3DHeader.colorLimits.colorRedMinimum, + data3DHeader.colorLimits.colorRedMaximum ); + _readColourRanges( "colorGreen", proto, data3DHeader.colorLimits.colorGreenMinimum, + data3DHeader.colorLimits.colorGreenMaximum ); + _readColourRanges( "colorBlue", proto, data3DHeader.colorLimits.colorBlueMinimum, + data3DHeader.colorLimits.colorBlueMaximum ); // E57_EXT_surface_normals - ustring norExtUri; - if ( imf_.extensionsLookupPrefix( "nor", norExtUri ) ) + // See: http://www.libe57.org/E57_EXT_surface_normals.txt + if ( imf_.extensionsLookupPrefix( "nor" ) ) { - data3DHeader.pointFields.normalX = proto.isDefined( "nor:normalX" ); - data3DHeader.pointFields.normalY = proto.isDefined( "nor:normalY" ); - data3DHeader.pointFields.normalZ = proto.isDefined( "nor:normalZ" ); + data3DHeader.pointFields.normalXField = proto.isDefined( "nor:normalX" ); + data3DHeader.pointFields.normalYField = proto.isDefined( "nor:normalY" ); + data3DHeader.pointFields.normalZField = proto.isDefined( "nor:normalZ" ); } return true; } // This function returns the size of the point data - bool ReaderImpl::GetData3DSizes( int64_t dataIndex, int64_t &row, int64_t &column, int64_t &pointsSize, - int64_t &groupsSize, int64_t &countSize, bool &bColumnIndex ) const + bool ReaderImpl::GetData3DSizes( int64_t dataIndex, int64_t &row, int64_t &column, + int64_t &pointsSize, int64_t &groupsSize, int64_t &countSize, + bool &bColumnIndex ) const { + int64_t elementSize = 0; + row = 0; column = 0; pointsSize = 0; groupsSize = 0; - int64_t elementSize = 0; countSize = 0; bColumnIndex = false; - if ( !IsOpen() ) - { - return false; - } - if ( ( dataIndex < 0 ) || ( dataIndex >= data3D_.childCount() ) ) + if ( !IsOpen() || ( dataIndex < 0 ) || ( dataIndex >= data3D_.childCount() ) ) { return false; } - StructureNode scan( data3D_.get( dataIndex ) ); + const StructureNode scan( data3D_.get( dataIndex ) ); + const CompressedVectorNode points( scan.get( "points" ) ); - CompressedVectorNode points( scan.get( "points" ) ); pointsSize = points.childCount(); if ( scan.isDefined( "indexBounds" ) ) { - StructureNode indexBounds( scan.get( "indexBounds" ) ); + const StructureNode indexBounds( scan.get( "indexBounds" ) ); + if ( indexBounds.isDefined( "columnMaximum" ) ) { column = IntegerNode( indexBounds.get( "columnMaximum" ) ).value() - @@ -1146,26 +1421,28 @@ namespace e57 if ( scan.isDefined( "pointGroupingSchemes" ) ) { - StructureNode pointGroupingSchemes( scan.get( "pointGroupingSchemes" ) ); + const StructureNode pointGroupingSchemes( scan.get( "pointGroupingSchemes" ) ); + if ( pointGroupingSchemes.isDefined( "groupingByLine" ) ) { - StructureNode groupingByLine( pointGroupingSchemes.get( "groupingByLine" ) ); + const StructureNode groupingByLine( pointGroupingSchemes.get( "groupingByLine" ) ); + const StringNode idElementName( groupingByLine.get( "idElementName" ) ); - StringNode idElementName( groupingByLine.get( "idElementName" ) ); - if ( idElementName.value().compare( "columnIndex" ) == 0 ) + if ( idElementName.value() == "columnIndex" ) { bColumnIndex = true; } - CompressedVectorNode groups( groupingByLine.get( "groups" ) ); - groupsSize = groups.childCount(); + const CompressedVectorNode groups( groupingByLine.get( "groups" ) ); + const StructureNode lineGroupRecord( groups.prototype() ); - StructureNode lineGroupRecord( groups.prototype() ); + groupsSize = groups.childCount(); if ( lineGroupRecord.isDefined( "idElementValue" ) ) { - elementSize = IntegerNode( lineGroupRecord.get( "idElementValue" ) ).maximum() - - IntegerNode( lineGroupRecord.get( "idElementValue" ) ).minimum() + 1; + const IntegerNode integerIDElementValue( lineGroupRecord.get( "idElementValue" ) ); + + elementSize = integerIDElementValue.maximum() - integerIDElementValue.minimum() + 1; } else if ( bColumnIndex ) { @@ -1218,55 +1495,56 @@ namespace e57 return true; } - // This function writes out the group data - bool ReaderImpl::ReadData3DGroupsData( int64_t dataIndex, int64_t groupCount, int64_t *idElementValue, - int64_t *startPointIndex, int64_t *pointCount ) const + // Reads the group data + bool ReaderImpl::ReadData3DGroupsData( int64_t dataIndex, size_t groupCount, + int64_t *idElementValue, int64_t *startPointIndex, + int64_t *pointCount ) const { if ( ( dataIndex < 0 ) || ( dataIndex >= data3D_.childCount() ) ) { return false; } - StructureNode scan( data3D_.get( dataIndex ) ); + const StructureNode scan( data3D_.get( dataIndex ) ); + if ( !scan.isDefined( "pointGroupingSchemes" ) ) { return false; } - StructureNode pointGroupingSchemes( scan.get( "pointGroupingSchemes" ) ); + const StructureNode pointGroupingSchemes( scan.get( "pointGroupingSchemes" ) ); + if ( !pointGroupingSchemes.isDefined( "groupingByLine" ) ) { return false; } - StructureNode groupingByLine( pointGroupingSchemes.get( "groupingByLine" ) ); - - StringNode idElementName( groupingByLine.get( "idElementName" ) ); + const StructureNode groupingByLine( pointGroupingSchemes.get( "groupingByLine" ) ); + const StringNode idElementName( groupingByLine.get( "idElementName" ) ); CompressedVectorNode groups( groupingByLine.get( "groups" ) ); - StructureNode lineGroupRecord( groups.prototype() ); // not used here - - int64_t protoCount = lineGroupRecord.childCount(); - int64_t protoIndex; + const StructureNode lineGroupRecord( groups.prototype() ); + const int64_t protoCount = lineGroupRecord.childCount(); std::vector groupSDBuffers; - for ( protoIndex = 0; protoIndex < protoCount; protoIndex++ ) + for ( int64_t protoIndex = 0; protoIndex < protoCount; protoIndex++ ) { - ustring name = lineGroupRecord.get( protoIndex ).elementName(); + const ustring name = lineGroupRecord.get( protoIndex ).elementName(); - if ( ( name.compare( "idElementValue" ) == 0 ) && lineGroupRecord.isDefined( "idElementValue" ) && - idElementValue ) + if ( ( name == "idElementValue" ) && lineGroupRecord.isDefined( "idElementValue" ) && + ( idElementValue != nullptr ) ) { groupSDBuffers.emplace_back( imf_, "idElementValue", idElementValue, groupCount, true ); } - if ( ( name.compare( "startPointIndex" ) == 0 ) && lineGroupRecord.isDefined( "startPointIndex" ) && - startPointIndex ) + if ( ( name == "startPointIndex" ) && lineGroupRecord.isDefined( "startPointIndex" ) && + ( startPointIndex != nullptr ) ) { - groupSDBuffers.emplace_back( imf_, "startPointIndex", startPointIndex, groupCount, true ); + groupSDBuffers.emplace_back( imf_, "startPointIndex", startPointIndex, groupCount, + true ); } - if ( ( name.compare( "pointCount" ) == 0 ) && lineGroupRecord.isDefined( "pointCount" ) && - pointCount ) + if ( ( name == "pointCount" ) && lineGroupRecord.isDefined( "pointCount" ) && + ( pointCount != nullptr ) ) { groupSDBuffers.emplace_back( imf_, "pointCount", pointCount, groupCount, true ); } @@ -1281,139 +1559,148 @@ namespace e57 } template - CompressedVectorReader ReaderImpl::SetUpData3DPointsData( int64_t dataIndex, size_t count, - const Data3DPointsData_t &buffers ) const + CompressedVectorReader ReaderImpl::SetUpData3DPointsData( + int64_t dataIndex, size_t count, const Data3DPointsData_t &buffers ) const { - StructureNode scan( data3D_.get( dataIndex ) ); - CompressedVectorNode points( scan.get( "points" ) ); - StructureNode proto( points.prototype() ); - - int64_t protoCount = proto.childCount(); - int64_t protoIndex; + static_assert( std::is_floating_point::value, "Floating point type required." ); + const StructureNode scan( data3D_.get( dataIndex ) ); + CompressedVectorNode points( scan.get( "points" ) ); + const StructureNode proto( points.prototype() ); + const int64_t protoCount = proto.childCount(); std::vector destBuffers; - for ( protoIndex = 0; protoIndex < protoCount; protoIndex++ ) + for ( int64_t protoIndex = 0; protoIndex < protoCount; protoIndex++ ) { - ustring name = proto.get( protoIndex ).elementName(); - NodeType type = proto.get( protoIndex ).type(); - bool scaled = (type == E57_SCALED_INTEGER); + const ustring name = proto.get( protoIndex ).elementName(); + const NodeType type = proto.get( protoIndex ).type(); + const bool scaled = ( type == TypeScaledInteger ); + // E57_EXT_surface_normals ustring norExtUri; - bool haveNormalsExt = imf_.extensionsLookupPrefix( "nor", norExtUri ); + const bool haveNormalsExt = imf_.extensionsLookupPrefix( "nor", norExtUri ); - if ( ( name.compare( "cartesianX" ) == 0 ) && proto.isDefined( "cartesianX" ) && - buffers.cartesianX ) + if ( ( name == "cartesianX" ) && proto.isDefined( "cartesianX" ) && + ( buffers.cartesianX != nullptr ) ) { destBuffers.emplace_back( imf_, "cartesianX", buffers.cartesianX, count, true, scaled ); } - else if ( ( name.compare( "cartesianY" ) == 0 ) && proto.isDefined( "cartesianY" ) && - buffers.cartesianY ) + else if ( ( name == "cartesianY" ) && proto.isDefined( "cartesianY" ) && + ( buffers.cartesianY != nullptr ) ) { destBuffers.emplace_back( imf_, "cartesianY", buffers.cartesianY, count, true, scaled ); } - else if ( ( name.compare( "cartesianZ" ) == 0 ) && proto.isDefined( "cartesianZ" ) && - buffers.cartesianZ ) + else if ( ( name == "cartesianZ" ) && proto.isDefined( "cartesianZ" ) && + ( buffers.cartesianZ != nullptr ) ) { destBuffers.emplace_back( imf_, "cartesianZ", buffers.cartesianZ, count, true, scaled ); } - else if ( ( name.compare( "cartesianInvalidState" ) == 0 ) && proto.isDefined( "cartesianInvalidState" ) && - buffers.cartesianInvalidState ) + else if ( ( name == "cartesianInvalidState" ) && + proto.isDefined( "cartesianInvalidState" ) && + ( buffers.cartesianInvalidState != nullptr ) ) { - destBuffers.emplace_back( imf_, "cartesianInvalidState", buffers.cartesianInvalidState, count, true ); + destBuffers.emplace_back( imf_, "cartesianInvalidState", buffers.cartesianInvalidState, + count, true ); } - else if ( ( name.compare( "sphericalRange" ) == 0 ) && proto.isDefined( "sphericalRange" ) && - buffers.sphericalRange ) + else if ( ( name == "sphericalRange" ) && proto.isDefined( "sphericalRange" ) && + ( buffers.sphericalRange != nullptr ) ) { - destBuffers.emplace_back( imf_, "sphericalRange", buffers.sphericalRange, count, true, scaled ); + destBuffers.emplace_back( imf_, "sphericalRange", buffers.sphericalRange, count, true, + scaled ); } - else if ( ( name.compare( "sphericalAzimuth" ) == 0 ) && proto.isDefined( "sphericalAzimuth" ) && - buffers.sphericalAzimuth ) + else if ( ( name == "sphericalAzimuth" ) && proto.isDefined( "sphericalAzimuth" ) && + ( buffers.sphericalAzimuth != nullptr ) ) { - destBuffers.emplace_back( imf_, "sphericalAzimuth", buffers.sphericalAzimuth, count, true, scaled ); + destBuffers.emplace_back( imf_, "sphericalAzimuth", buffers.sphericalAzimuth, count, + true, scaled ); } - else if ( ( name.compare( "sphericalElevation" ) == 0 ) && proto.isDefined( "sphericalElevation" ) && - buffers.sphericalElevation ) + else if ( ( name == "sphericalElevation" ) && proto.isDefined( "sphericalElevation" ) && + ( buffers.sphericalElevation != nullptr ) ) { - destBuffers.emplace_back( imf_, "sphericalElevation", buffers.sphericalElevation, count, true, scaled ); + destBuffers.emplace_back( imf_, "sphericalElevation", buffers.sphericalElevation, count, + true, scaled ); } - else if ( ( name.compare( "sphericalInvalidState" ) == 0 ) && proto.isDefined( "sphericalInvalidState" ) && - buffers.sphericalInvalidState ) + else if ( ( name == "sphericalInvalidState" ) && + proto.isDefined( "sphericalInvalidState" ) && + ( buffers.sphericalInvalidState != nullptr ) ) { - destBuffers.emplace_back( imf_, "sphericalInvalidState", buffers.sphericalInvalidState, count, true ); + destBuffers.emplace_back( imf_, "sphericalInvalidState", buffers.sphericalInvalidState, + count, true ); } - else if ( ( name.compare( "rowIndex" ) == 0 ) && proto.isDefined( "rowIndex" ) && - buffers.rowIndex ) + else if ( ( name == "rowIndex" ) && proto.isDefined( "rowIndex" ) && + ( buffers.rowIndex != nullptr ) ) { destBuffers.emplace_back( imf_, "rowIndex", buffers.rowIndex, count, true ); } - else if ( ( name.compare( "columnIndex" ) == 0 ) && proto.isDefined( "columnIndex" ) && - buffers.columnIndex ) + else if ( ( name == "columnIndex" ) && proto.isDefined( "columnIndex" ) && + ( buffers.columnIndex != nullptr ) ) { destBuffers.emplace_back( imf_, "columnIndex", buffers.columnIndex, count, true ); } - else if ( ( name.compare( "returnIndex" ) == 0 ) && proto.isDefined( "returnIndex" ) && - buffers.returnIndex ) + else if ( ( name == "returnIndex" ) && proto.isDefined( "returnIndex" ) && + ( buffers.returnIndex != nullptr ) ) { destBuffers.emplace_back( imf_, "returnIndex", buffers.returnIndex, count, true ); } - else if ( ( name.compare( "returnCount" ) == 0 ) && proto.isDefined( "returnCount" ) && - buffers.returnCount ) + else if ( ( name == "returnCount" ) && proto.isDefined( "returnCount" ) && + ( buffers.returnCount != nullptr ) ) { destBuffers.emplace_back( imf_, "returnCount", buffers.returnCount, count, true ); } - else if ( ( name.compare( "timeStamp" ) == 0 ) && proto.isDefined( "timeStamp" ) && - buffers.timeStamp ) + else if ( ( name == "timeStamp" ) && proto.isDefined( "timeStamp" ) && + ( buffers.timeStamp != nullptr ) ) { destBuffers.emplace_back( imf_, "timeStamp", buffers.timeStamp, count, true, scaled ); } - else if ( ( name.compare( "isTimeStampInvalid" ) == 0 ) && proto.isDefined( "isTimeStampInvalid" ) && - buffers.isTimeStampInvalid ) + else if ( ( name == "isTimeStampInvalid" ) && proto.isDefined( "isTimeStampInvalid" ) && + ( buffers.isTimeStampInvalid != nullptr ) ) { - destBuffers.emplace_back( imf_, "isTimeStampInvalid", buffers.isTimeStampInvalid, count, true ); + destBuffers.emplace_back( imf_, "isTimeStampInvalid", buffers.isTimeStampInvalid, count, + true ); } - else if ( ( name.compare( "intensity" ) == 0 ) && proto.isDefined( "intensity" ) && - buffers.intensity ) + else if ( ( name == "intensity" ) && proto.isDefined( "intensity" ) && + ( buffers.intensity != nullptr ) ) { destBuffers.emplace_back( imf_, "intensity", buffers.intensity, count, true, scaled ); } - else if ( ( name.compare( "isIntensityInvalid" ) == 0 ) && proto.isDefined( "isIntensityInvalid" ) && - buffers.isIntensityInvalid ) + else if ( ( name == "isIntensityInvalid" ) && proto.isDefined( "isIntensityInvalid" ) && + ( buffers.isIntensityInvalid != nullptr ) ) { - destBuffers.emplace_back( imf_, "isIntensityInvalid", buffers.isIntensityInvalid, count, true ); + destBuffers.emplace_back( imf_, "isIntensityInvalid", buffers.isIntensityInvalid, count, + true ); } - else if ( ( name.compare( "colorRed" ) == 0 ) && proto.isDefined( "colorRed" ) && - buffers.colorRed ) + else if ( ( name == "colorRed" ) && proto.isDefined( "colorRed" ) && + ( buffers.colorRed != nullptr ) ) { destBuffers.emplace_back( imf_, "colorRed", buffers.colorRed, count, true, scaled ); } - else if ( ( name.compare( "colorGreen" ) == 0 ) && proto.isDefined( "colorGreen" ) && - buffers.colorGreen ) + else if ( ( name == "colorGreen" ) && proto.isDefined( "colorGreen" ) && + ( buffers.colorGreen != nullptr ) ) { destBuffers.emplace_back( imf_, "colorGreen", buffers.colorGreen, count, true, scaled ); } - else if ( ( name.compare( "colorBlue" ) == 0 ) && proto.isDefined( "colorBlue" ) && - buffers.colorBlue ) + else if ( ( name == "colorBlue" ) && proto.isDefined( "colorBlue" ) && + ( buffers.colorBlue != nullptr ) ) { destBuffers.emplace_back( imf_, "colorBlue", buffers.colorBlue, count, true, scaled ); } - else if ( ( name.compare( "isColorInvalid" ) == 0 ) && proto.isDefined( "isColorInvalid" ) && - buffers.isColorInvalid ) + else if ( ( name == "isColorInvalid" ) && proto.isDefined( "isColorInvalid" ) && + ( buffers.isColorInvalid != nullptr ) ) { destBuffers.emplace_back( imf_, "isColorInvalid", buffers.isColorInvalid, count, true ); } - else if ( haveNormalsExt && ( name.compare( "nor:normalX" ) == 0 ) && proto.isDefined( "nor:normalX" ) && - buffers.normalX ) + else if ( haveNormalsExt && ( name == "nor:normalX" ) && + proto.isDefined( "nor:normalX" ) && ( buffers.normalX != nullptr ) ) { destBuffers.emplace_back( imf_, "nor:normalX", buffers.normalX, count, true, scaled ); } - else if ( haveNormalsExt && ( name.compare( "nor:normalY" ) == 0 ) && proto.isDefined( "nor:normalY" ) && - buffers.normalY ) + else if ( haveNormalsExt && ( name == "nor:normalY" ) && + proto.isDefined( "nor:normalY" ) && ( buffers.normalY != nullptr ) ) { destBuffers.emplace_back( imf_, "nor:normalY", buffers.normalY, count, true, scaled ); } - else if ( haveNormalsExt && ( name.compare( "nor:normalZ" ) == 0 ) && proto.isDefined( "nor:normalZ" ) && - buffers.normalZ ) + else if ( haveNormalsExt && ( name == "nor:normalZ" ) && + proto.isDefined( "nor:normalZ" ) && ( buffers.normalZ != nullptr ) ) { destBuffers.emplace_back( imf_, "nor:normalZ", buffers.normalZ, count, true, scaled ); } @@ -1424,11 +1711,36 @@ namespace e57 return reader; } + int64_t ReaderImpl::GetData3DCount() const + { + return data3D_.childCount(); + } + + StructureNode ReaderImpl::GetRawE57Root() const + { + return root_; + } + + VectorNode ReaderImpl::GetRawData3D() const + { + return data3D_; + } + + VectorNode ReaderImpl::GetRawImages2D() const + { + return images2D_; + } + + ImageFile ReaderImpl::GetRawIMF() const + { + return imf_; + } + // Explicit template instantiation - template CompressedVectorReader ReaderImpl::SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData_t &buffers ) const; + template CompressedVectorReader ReaderImpl::SetUpData3DPointsData( + int64_t dataIndex, size_t pointCount, const Data3DPointsData_t &buffers ) const; - template CompressedVectorReader ReaderImpl::SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData_t &buffers ) const; + template CompressedVectorReader ReaderImpl::SetUpData3DPointsData( + int64_t dataIndex, size_t pointCount, const Data3DPointsData_t &buffers ) const; } // end namespace e57 diff --git a/src/3rdParty/libE57Format/src/ReaderImpl.h b/src/3rdParty/libE57Format/src/ReaderImpl.h index 6570beb5fa624..33d455e2d1fd7 100644 --- a/src/3rdParty/libE57Format/src/ReaderImpl.h +++ b/src/3rdParty/libE57Format/src/ReaderImpl.h @@ -1,6 +1,7 @@ /* * Copyright (c) 2010 Stan Coleby (scoleby@intelisum.com) * Copyright (c) 2020 PTC Inc. + * Copyright (c) 2022 Andy Maloney * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by @@ -28,18 +29,22 @@ #pragma once #include "E57SimpleData.h" +#include "E57SimpleReader.h" namespace e57 { - - //! most of the functions follows Reader class ReaderImpl { public: - ReaderImpl( const ustring &filePath ); - + explicit ReaderImpl( const ustring &filePath, const ReaderOptions &options ); ~ReaderImpl(); + // disallow copying a ReaderImpl + ReaderImpl( const ReaderImpl & ) = delete; + ReaderImpl &operator=( ReaderImpl const & ) = delete; + ReaderImpl( const ReaderImpl && ) = delete; + ReaderImpl &operator=( const ReaderImpl && ) = delete; + bool IsOpen() const; bool Close(); @@ -50,26 +55,29 @@ namespace e57 bool ReadImage2D( int64_t imageIndex, Image2D &Image2DHeader ) const; - bool GetImage2DSizes( int64_t imageIndex, Image2DProjection &imageProjection, Image2DType &imageType, - int64_t &imageWidth, int64_t &imageHeight, int64_t &imageSize, Image2DType &imageMaskType, + bool GetImage2DSizes( int64_t imageIndex, Image2DProjection &imageProjection, + Image2DType &imageType, int64_t &imageWidth, int64_t &imageHeight, + int64_t &imageSize, Image2DType &imageMaskType, Image2DType &imageVisualType ) const; - int64_t ReadImage2DData( int64_t imageIndex, Image2DProjection imageProjection, Image2DType imageType, - void *pBuffer, int64_t start, int64_t count ) const; + size_t ReadImage2DData( int64_t imageIndex, Image2DProjection imageProjection, + Image2DType imageType, uint8_t *pBuffer, int64_t start, + size_t count ) const; int64_t GetData3DCount() const; bool ReadData3D( int64_t dataIndex, Data3D &data3DHeader ) const; - bool GetData3DSizes( int64_t dataIndex, int64_t &rowMax, int64_t &columnMax, int64_t &pointsSize, - int64_t &groupsSize, int64_t &countSize, bool &bColumnIndex ) const; + bool GetData3DSizes( int64_t dataIndex, int64_t &rowMax, int64_t &columnMax, + int64_t &pointsSize, int64_t &groupsSize, int64_t &countSize, + bool &bColumnIndex ) const; - bool ReadData3DGroupsData( int64_t dataIndex, int64_t groupCount, int64_t *idElementValue, + bool ReadData3DGroupsData( int64_t dataIndex, size_t groupCount, int64_t *idElementValue, int64_t *startPointIndex, int64_t *pointCount ) const; template - CompressedVectorReader SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData_t &buffers ) const; + CompressedVectorReader SetUpData3DPointsData( + int64_t dataIndex, size_t pointCount, const Data3DPointsData_t &buffers ) const; StructureNode GetRawE57Root() const; @@ -86,27 +94,5 @@ namespace e57 VectorNode data3D_; VectorNode images2D_; - - //! @brief This function reads one of the image blobs - //! @param [in] image 1 of 3 projects or the visual - //! @param [out] imageType identifies the image format desired. - //! @param [out] imageWidth The image width (in pixels). - //! @param [out] imageHeight The image height (in pixels). - //! @param [out] imageSize This is the total number of bytes for the image blob. - //! @param [out] imageMaskType This is E57_PNG_IMAGE_MASK if "imageMask" is defined in the projection - //! @return Returns true if successful - bool GetImage2DNodeSizes( StructureNode image, Image2DType &imageType, int64_t &imageWidth, int64_t &imageHeight, - int64_t &imageSize, Image2DType &imageMaskType ) const; - - //! @brief Reads the data out of a given image node - //! @param [in] image 1 of 3 projects or the visual - //! @param [in] imageType identifies the image format desired. - //! @param [out] pBuffer pointer the buffer - //! @param [out] start position in the block to start reading - //! @param [out] count size of desired chuck or buffer size - //! @return number of bytes read - int64_t ReadImage2DNode( StructureNode image, Image2DType imageType, void *pBuffer, int64_t start, - int64_t count ) const; }; // end Reader class - } // end namespace e57 diff --git a/src/3rdParty/libE57Format/src/ScaledIntegerNode.cpp b/src/3rdParty/libE57Format/src/ScaledIntegerNode.cpp new file mode 100644 index 0000000000000..c20cf8dc70322 --- /dev/null +++ b/src/3rdParty/libE57Format/src/ScaledIntegerNode.cpp @@ -0,0 +1,481 @@ +/* + * ScaledIntegerNode.cpp - implementation of public functions of the ScaledIntegerNode class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file ScaledIntegerNode.cpp + +#include "ScaledIntegerNodeImpl.h" +#include "StringFunctions.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/*! +@brief Check whether ScaledIntegerNode class invariant is true +@copydetails IntegerNode::checkInvariant() +*/ +void ScaledIntegerNode::checkInvariant( bool /*doRecurse*/, bool doUpcast ) const +{ + // If destImageFile not open, can't test invariant (almost every call would throw) + if ( !destImageFile().isOpen() ) + { + return; + } + + // If requested, call Node::checkInvariant + if ( doUpcast ) + { + static_cast( *this ).checkInvariant( false, false ); + } + + // If value is out of bounds + if ( rawValue() < minimum() || rawValue() > maximum() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // If scale is zero + if ( scale() == 0 ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // If scaled value is not calculated correctly + if ( scaledValue() != rawValue() * scale() + offset() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } +} + +/*! +@class e57::ScaledIntegerNode + +@brief An E57 element encoding a fixed point number. + +@details +An ScaledIntegerNode is a terminal node (i.e. having no children) that holds a fixed point number +encoded by an integer @c rawValue, a double precision floating point @c scale, an double precision +floating point @c offset, and integer minimum/maximum bounds. + +The @c minimum attribute may be a number in the interval [-2^63, 2^63). + +The @c maximum attribute may be a number in the interval [minimum, 2^63). + +The @c rawValue may be a number in the interval [minimum, maximum]. + +The @c scaledValue is a calculated double precision floating point number derived from: scaledValue += rawValue*scale + offset. + +See Node class discussion for discussion of the common functions that StructureNode supports. + +@section ScaledIntegerNode_invariant Class Invariant +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude ScaledIntegerNode.cpp +@skip void ScaledIntegerNode::checkInvariant +@until ^} + +@see Node +*/ + +/*! +@brief Create an E57 element for storing a fixed point number. + +@param [in] destImageFile The ImageFile where the new node will eventually be stored. +@param [in] rawValue The raw integer value of the element. +@param [in] minimum The smallest rawValue that the element may take. +@param [in] maximum The largest rawValue that the element may take. +@param [in] scale The scaling factor used to compute scaledValue from rawValue. +@param [in] offset The offset factor used to compute scaledValue from rawValue. + +@details +A ScaledIntegerNode stores an integer value, a lower and upper bound, and two conversion factors. +The ScaledIntegerNode class corresponds to the ASTM E57 standard ScaledInteger element. See the +class discussion at bottom of ScaledIntegerNode page for more details. + +The @a destImageFile indicates which ImageFile the ScaledIntegerNode will eventually be attached to. +A node is attached to an ImageFile by adding it underneath the predefined root of the ImageFile +(gotten from ImageFile::root). It is not an error to fail to attach the ScaledIntegerNode to the @a +destImageFile. It is an error to attempt to attach the ScaledIntegerNode to a different ImageFile. + +@warning It is an error to give an @a rawValue outside the @a minimum / @a maximum bounds, even if +the ScaledIntegerNode is destined to be used in a CompressedVectorNode prototype (where the @a +rawValue will be ignored). If the ScaledIntegerNode is to be used in a prototype, it is recommended +to specify a @a rawValue = 0 if 0 is within bounds, or a @a rawValue = @a minimum if 0 is not within +bounds. + +@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be true). +@pre The @a destImageFile must have been opened in write mode (i.e. destImageFile.isWritable() must +be true). +@pre minimum <= rawValue <= maximum +@pre scale != 0 + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorFileReadOnly +@throw ::ErrorValueOutOfBounds +@throw ::ErrorInternal All objects in undocumented state + +@see ScaledIntegerNode::rawValue, Node, CompressedVectorNode, CompressedVectorNode::prototype +*/ +ScaledIntegerNode::ScaledIntegerNode( const ImageFile &destImageFile, int64_t rawValue, + int64_t minimum, int64_t maximum, double scale, + double offset ) : + impl_( + new ScaledIntegerNodeImpl( destImageFile.impl(), rawValue, minimum, maximum, scale, offset ) ) +{ +} + +ScaledIntegerNode::ScaledIntegerNode( const ImageFile &destImageFile, int rawValue, int64_t minimum, + int64_t maximum, double scale, double offset ) : + impl_( new ScaledIntegerNodeImpl( destImageFile.impl(), static_cast( rawValue ), + minimum, maximum, scale, offset ) ) +{ +} + +ScaledIntegerNode::ScaledIntegerNode( const ImageFile &destImageFile, int rawValue, int minimum, + int maximum, double scale, double offset ) : + impl_( new ScaledIntegerNodeImpl( destImageFile.impl(), static_cast( rawValue ), + static_cast( minimum ), + static_cast( maximum ), scale, offset ) ) +{ +} + +/*! +@brief This second constructor creates an E57 element for storing a fixed point number but does the +scaling for you. + +@param [in] destImageFile The ImageFile where the new node will eventually be stored. +@param [in] scaledValue The scaled integer value of the element. +@param [in] scaledMinimum The smallest scaledValue that the element may take. +@param [in] scaledMaximum The largest scaledValue that the element may take. +@param [in] scale The scaling factor used to compute scaledValue from rawValue. +@param [in] offset The offset factor used to compute scaledValue from rawValue. + +@details +A ScaledIntegerNode stores an integer value, a lower and upper bound, and two conversion factors. +This ScaledIntegerNode constructor calculates the rawValue, minimum, and maximum by doing the +floor((scaledValue - offset)/scale + .5) on each scaled parameters. + +@warning It is an error to give an @a rawValue outside the @a minimum / @a maximum bounds, even if +the ScaledIntegerNode is destined to be used in a CompressedVectorNode prototype (where the @a +rawValue will be ignored). If the ScaledIntegerNode is to be used in a prototype, it is recommended +to specify a @a rawValue = 0 if 0 is within bounds, or a @a rawValue = @a minimum if 0 is not within +bounds. + +@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be true). +@pre The @a destImageFile must have been opened in write mode (i.e. destImageFile.isWritable() must +be true). +@pre scaledMinimum <= scaledValue <= scaledMaximum +@pre scale != 0 + +@throw ::ErrorBadAPIArgument +@throw ::ErrorImageFileNotOpen +@throw ::ErrorFileReadOnly +@throw ::ErrorValueOutOfBounds +@throw ::ErrorInternal All objects in undocumented state + +@see ScaledIntegerNode::scaledValue, Node, CompressedVectorNode, CompressedVectorNode::prototype +*/ +ScaledIntegerNode::ScaledIntegerNode( const ImageFile &destImageFile, double scaledValue, + double scaledMinimum, double scaledMaximum, double scale, + double offset ) : + impl_( new ScaledIntegerNodeImpl( destImageFile.impl(), scaledValue, scaledMinimum, + scaledMaximum, scale, offset ) ) +{ +} + +/*! +@brief Is this a root node. +@copydetails Node::isRoot() +*/ +bool ScaledIntegerNode::isRoot() const +{ + return impl_->isRoot(); +} + +/*! +@brief Return parent of node, or self if a root node. +@copydetails Node::parent() +*/ +Node ScaledIntegerNode::parent() const +{ + return Node( impl_->parent() ); +} + +/*! +@brief Get absolute pathname of node. +@copydetails Node::pathName() +*/ +ustring ScaledIntegerNode::pathName() const +{ + return impl_->pathName(); +} + +/*! +@brief Get elementName string, that identifies the node in its parent. +@copydetails Node::elementName() +*/ +ustring ScaledIntegerNode::elementName() const +{ + return impl_->elementName(); +} + +/*! +@brief Get the ImageFile that was declared as the destination for the node when it was created. +@copydetails Node::destImageFile() +*/ +ImageFile ScaledIntegerNode::destImageFile() const +{ + return ImageFile( impl_->destImageFile() ); +} + +/*! +@brief Has node been attached into the tree of an ImageFile. +@copydetails Node::isAttached() +*/ +bool ScaledIntegerNode::isAttached() const +{ + return impl_->isAttached(); +} + +/*! +@brief Get raw unscaled integer value of element. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The raw unscaled integer value stored. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ScaledIntegerNode::scaledValue, ScaledIntegerNode::minimum, ScaledIntegerNode::maximum +*/ +int64_t ScaledIntegerNode::rawValue() const +{ + return impl_->rawValue(); +} + +/*! +@brief Get scaled value of element. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The scaled value (rawValue*scale + offset) calculated from the rawValue stored. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ScaledIntegerNode::rawValue +*/ +double ScaledIntegerNode::scaledValue() const +{ + return impl_->scaledValue(); +} + +/*! +@brief Get the declared minimum that the raw value may take. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The declared minimum that the rawValue may take. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ScaledIntegerNode::maximum, ScaledIntegerNode::rawValue +*/ +int64_t ScaledIntegerNode::minimum() const +{ + return impl_->minimum(); +} + +/*! +@brief Get the declared scaled minimum that the scaled value may take. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The declared minimum that the rawValue may take. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ScaledIntegerNode::scaledMaximum, ScaledIntegerNode::scaledValue +*/ +double ScaledIntegerNode::scaledMinimum() const +{ + return impl_->scaledMinimum(); +} + +/*! +@brief Get the declared maximum that the raw value may take. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The declared maximum that the rawValue may take. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ScaledIntegerNode::minimum, ScaledIntegerNode::rawValue +*/ +int64_t ScaledIntegerNode::maximum() const +{ + return impl_->maximum(); +} + +/*! +@brief Get the declared scaled maximum that the scaled value may take. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The declared maximum that the rawValue may take. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ScaledIntegerNode::scaledMinimum, ScaledIntegerNode::scaledValue +*/ +double ScaledIntegerNode::scaledMaximum() const // Added by SC +{ + return impl_->scaledMaximum(); +} + +/*! +@brief Get declared scaling factor. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The scaling factor used to compute scaledValue from rawValue. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ScaledIntegerNode::scaledValue +*/ +double ScaledIntegerNode::scale() const +{ + return impl_->scale(); +} + +/*! +@brief Get declared offset. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return The offset used to compute scaledValue from rawValue. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ScaledIntegerNode::scaledValue +*/ +double ScaledIntegerNode::offset() const +{ + return impl_->offset(); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void ScaledIntegerNode::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void ScaledIntegerNode::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif + +/*! +@brief Upcast a ScaledIntegerNode handle to a generic Node handle. + +@details +An upcast is always safe, and the compiler can automatically insert it for initializations of Node +variables and Node function arguments. + +@return A smart Node handle referencing the underlying object. + +@throw No E57Exceptions. + +@see Explanation in Node, Node::type(), ScaledIntegerNode(const Node&) +*/ +ScaledIntegerNode::operator Node() const +{ + // Upcast from shared_ptr to SharedNodeImplPtr and construct a Node object + return Node( impl_ ); +} + +/*! +@brief Downcast a generic Node handle to an ScaledIntegerNode handle. + +@param [in] n The generic handle to downcast. + +@details +The handle @a n must be for an underlying ScaledIntegerNode, otherwise an exception is thrown. In +designs that need to avoid the exception, use Node::type() to determine the actual type of the @a n +before downcasting. This function must be explicitly called (c++ compiler cannot insert it +automatically). + +@throw ::ErrorBadNodeDowncast + +@see Node::type(), ScaledIntegerNode::operator, Node() +*/ +ScaledIntegerNode::ScaledIntegerNode( const Node &n ) +{ + if ( n.type() != TypeScaledInteger ) + { + throw E57_EXCEPTION2( ErrorBadNodeDowncast, "nodeType=" + toString( n.type() ) ); + } + + // Set our shared_ptr to the downcast shared_ptr + impl_ = std::static_pointer_cast( n.impl() ); +} + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +ScaledIntegerNode::ScaledIntegerNode( std::shared_ptr ni ) : impl_( ni ) +{ +} +/// @endcond diff --git a/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.cpp b/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.cpp index 90c40c6873b7a..f90c69a2e67c2 100644 --- a/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.cpp @@ -29,43 +29,49 @@ #include "CheckedFile.h" #include "ScaledIntegerNodeImpl.h" +#include "StringFunctions.h" namespace e57 { - ScaledIntegerNodeImpl::ScaledIntegerNodeImpl( ImageFileImplWeakPtr destImageFile, int64_t rawValue, int64_t minimum, - int64_t maximum, double scale, double offset ) : + ScaledIntegerNodeImpl::ScaledIntegerNodeImpl( ImageFileImplWeakPtr destImageFile, + int64_t rawValue, int64_t minimum, int64_t maximum, + double scale, double offset ) : NodeImpl( destImageFile ), - value_( rawValue ), minimum_( minimum ), maximum_( maximum ), scale_( scale ), offset_( offset ) + value_( rawValue ), minimum_( minimum ), maximum_( maximum ), scale_( scale ), + offset_( offset ) { // don't checkImageFileOpen, NodeImpl() will do it - /// Enforce the given bounds on raw value + // Enforce the given bounds on raw value if ( rawValue < minimum || maximum < rawValue ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_OUT_OF_BOUNDS, - "this->pathName=" + this->pathName() + " rawValue=" + toString( rawValue ) + - " minimum=" + toString( minimum ) + " maximum=" + toString( maximum ) ); + throw E57_EXCEPTION2( ErrorValueOutOfBounds, "this->pathName=" + this->pathName() + + " rawValue=" + toString( rawValue ) + + " minimum=" + toString( minimum ) + + " maximum=" + toString( maximum ) ); } } - ScaledIntegerNodeImpl::ScaledIntegerNodeImpl( ImageFileImplWeakPtr destImageFile, double scaledValue, - double scaledMinimum, double scaledMaximum, double scale, + ScaledIntegerNodeImpl::ScaledIntegerNodeImpl( ImageFileImplWeakPtr destImageFile, + double scaledValue, double scaledMinimum, + double scaledMaximum, double scale, double offset ) : NodeImpl( destImageFile ), value_( static_cast( std::floor( ( scaledValue - offset ) / scale + .5 ) ) ), minimum_( static_cast( std::floor( ( scaledMinimum - offset ) / scale + .5 ) ) ), - maximum_( static_cast( std::floor( ( scaledMaximum - offset ) / scale + .5 ) ) ), scale_( scale ), - offset_( offset ) + maximum_( static_cast( std::floor( ( scaledMaximum - offset ) / scale + .5 ) ) ), + scale_( scale ), offset_( offset ) { // don't checkImageFileOpen, NodeImpl() will do it - /// Enforce the given bounds on raw value + // Enforce the given bounds on raw value if ( scaledValue < scaledMinimum || scaledMaximum < scaledValue ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_OUT_OF_BOUNDS, "this->pathName=" + this->pathName() + - " scaledValue=" + toString( scaledValue ) + - " scaledMinimum=" + toString( scaledMinimum ) + - " scaledMaximum=" + toString( scaledMaximum ) ); + throw E57_EXCEPTION2( ErrorValueOutOfBounds, + "this->pathName=" + this->pathName() + + " scaledValue=" + toString( scaledValue ) + + " scaledMinimum=" + toString( scaledMinimum ) + + " scaledMaximum=" + toString( scaledMaximum ) ); } } @@ -73,42 +79,43 @@ namespace e57 { // don't checkImageFileOpen - /// Same node type? - if ( ni->type() != E57_SCALED_INTEGER ) + // Same node type? + if ( ni->type() != TypeScaledInteger ) { return ( false ); } - /// Downcast to shared_ptr - std::shared_ptr ii( std::static_pointer_cast( ni ) ); + // Downcast to shared_ptr + std::shared_ptr ii( + std::static_pointer_cast( ni ) ); - /// minimum must match + // minimum must match if ( minimum_ != ii->minimum_ ) { return ( false ); } - /// maximum must match + // maximum must match if ( maximum_ != ii->maximum_ ) { return ( false ); } - /// scale must match + // scale must match if ( scale_ != ii->scale_ ) { return ( false ); } - /// offset must match + // offset must match if ( offset_ != ii->offset_ ) { return ( false ); } - /// ignore value_, doesn't have to match + // ignore value_, doesn't have to match - /// Types match + // Types match return ( true ); } @@ -116,7 +123,7 @@ namespace e57 { // don't checkImageFileOpen - /// We have no sub-structure, so if path not empty return false + // We have no sub-structure, so if path not empty return false return pathName.empty(); } @@ -137,6 +144,7 @@ namespace e57 checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); return ( minimum_ ); } + double ScaledIntegerNodeImpl::scaledMinimum() { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); @@ -148,6 +156,7 @@ namespace e57 checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); return ( maximum_ ); } + double ScaledIntegerNodeImpl::scaledMaximum() { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); @@ -166,24 +175,25 @@ namespace e57 return ( offset_ ); } - void ScaledIntegerNodeImpl::checkLeavesInSet( const StringSet &pathNames, NodeImplSharedPtr origin ) + void ScaledIntegerNodeImpl::checkLeavesInSet( const StringSet &pathNames, + NodeImplSharedPtr origin ) { // don't checkImageFileOpen - /// We are a leaf node, so verify that we are listed in set. + // We are a leaf node, so verify that we are listed in set. if ( pathNames.find( relativePathName( origin ) ) == pathNames.end() ) { - throw E57_EXCEPTION2( E57_ERROR_NO_BUFFER_FOR_ELEMENT, "this->pathName=" + this->pathName() ); + throw E57_EXCEPTION2( ErrorNoBufferForElement, "this->pathName=" + this->pathName() ); } } - void ScaledIntegerNodeImpl::writeXml( ImageFileImplSharedPtr /*imf*/, CheckedFile &cf, int indent, - const char *forcedFieldName ) + void ScaledIntegerNodeImpl::writeXml( ImageFileImplSharedPtr /*imf*/, CheckedFile &cf, + int indent, const char *forcedFieldName ) { // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName ) + if ( forcedFieldName != nullptr ) { fieldName = forcedFieldName; } @@ -194,12 +204,12 @@ namespace e57 cf << space( indent ) << "<" << fieldName << " type=\"ScaledInteger\""; - /// Don't need to write if are default values - if ( minimum_ != E57_INT64_MIN ) + // Don't need to write if are default values + if ( minimum_ != INT64_MIN ) { cf << " minimum=\"" << minimum_ << "\""; } - if ( maximum_ != E57_INT64_MAX ) + if ( maximum_ != INT64_MAX ) { cf << " maximum=\"" << maximum_ << "\""; } @@ -212,7 +222,7 @@ namespace e57 cf << " offset=\"" << offset_ << "\""; } - /// Write value as child text, unless it is the default value + // Write value as child text, unless it is the default value if ( value_ != 0 ) { cf << ">" << value_ << "\n"; @@ -223,7 +233,7 @@ namespace e57 } } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void ScaledIntegerNodeImpl::dump( int indent, std::ostream &os ) const { // don't checkImageFileOpen diff --git a/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.h b/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.h index 427a023c88de8..b6b5e1647144d 100644 --- a/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.h +++ b/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.h @@ -33,18 +33,21 @@ namespace e57 class ScaledIntegerNodeImpl : public NodeImpl { public: - ScaledIntegerNodeImpl( ImageFileImplWeakPtr destImageFile, int64_t value = 0, int64_t minimum = 0, - int64_t maximum = 0, double scale = 1.0, double offset = 0.0 ); + explicit ScaledIntegerNodeImpl( ImageFileImplWeakPtr destImageFile, int64_t value = 0, + int64_t minimum = 0, int64_t maximum = 0, double scale = 1.0, + double offset = 0.0 ); - ScaledIntegerNodeImpl( ImageFileImplWeakPtr destImageFile, double scaledValue = 0., double scaledMinimum = 0., - double scaledMaximum = 0., double scale = 1.0, double offset = 0.0 ); + explicit ScaledIntegerNodeImpl( ImageFileImplWeakPtr destImageFile, double scaledValue = 0., + double scaledMinimum = 0., double scaledMaximum = 0., + double scale = 1.0, double offset = 0.0 ); ~ScaledIntegerNodeImpl() override = default; NodeType type() const override { - return E57_SCALED_INTEGER; + return TypeScaledInteger; } + bool isTypeEquivalent( NodeImplSharedPtr ni ) override; bool isDefined( const ustring &pathName ) override; @@ -62,7 +65,7 @@ namespace e57 void writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, const char *forcedFieldName = nullptr ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif diff --git a/src/3rdParty/libE57Format/src/SectionHeaders.cpp b/src/3rdParty/libE57Format/src/SectionHeaders.cpp index 6b4cd588a0974..297f65a239014 100644 --- a/src/3rdParty/libE57Format/src/SectionHeaders.cpp +++ b/src/3rdParty/libE57Format/src/SectionHeaders.cpp @@ -26,11 +26,12 @@ */ #include "SectionHeaders.h" +#include "StringFunctions.h" namespace e57 { -#ifdef E57_DEBUG - void BlobSectionHeader::dump( int indent, std::ostream &os ) +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT + void BlobSectionHeader::dump( int indent, std::ostream &os ) const { os << space( indent ) << "sectionId: " << sectionId << std::endl; os << space( indent ) << "sectionLogicalLength: " << sectionLogicalLength << std::endl; @@ -39,56 +40,60 @@ namespace e57 CompressedVectorSectionHeader::CompressedVectorSectionHeader() { - /// Double check that header is correct length. Watch out for RTTI - /// increasing the size. + // Double check that header is correct length. Watch out for RTTI increasing the size. static_assert( sizeof( CompressedVectorSectionHeader ) == 32, "Unexpected size of CompressedVectorSectionHeader" ); } void CompressedVectorSectionHeader::verify( uint64_t filePhysicalSize ) { - /// Verify reserved fields are zero. ??? if fileversion==1.0 ??? + // Verify reserved fields are zero. ??? if fileversion==1.0 ??? for ( unsigned i = 0; i < sizeof( reserved1 ); i++ ) { if ( reserved1[i] != 0 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_HEADER, + throw E57_EXCEPTION2( ErrorBadCVHeader, "i=" + toString( i ) + " reserved=" + toString( reserved1[i] ) ); } } - /// Check section length is multiple of 4 + // Check section length is multiple of 4 if ( sectionLogicalLength % 4 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_HEADER, "sectionLogicalLength=" + toString( sectionLogicalLength ) ); + throw E57_EXCEPTION2( ErrorBadCVHeader, + "sectionLogicalLength=" + toString( sectionLogicalLength ) ); } - /// Check sectionLogicalLength is in bounds + // Check sectionLogicalLength is in bounds if ( filePhysicalSize > 0 && sectionLogicalLength >= filePhysicalSize ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_HEADER, "sectionLogicalLength=" + toString( sectionLogicalLength ) + - " filePhysicalSize=" + toString( filePhysicalSize ) ); + throw E57_EXCEPTION2( ErrorBadCVHeader, + "sectionLogicalLength=" + toString( sectionLogicalLength ) + + " filePhysicalSize=" + toString( filePhysicalSize ) ); } - /// Check dataPhysicalOffset is in bounds + // Check dataPhysicalOffset is in bounds if ( filePhysicalSize > 0 && dataPhysicalOffset >= filePhysicalSize ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_HEADER, "dataPhysicalOffset=" + toString( dataPhysicalOffset ) + - " filePhysicalSize=" + toString( filePhysicalSize ) ); + throw E57_EXCEPTION2( ErrorBadCVHeader, + "dataPhysicalOffset=" + toString( dataPhysicalOffset ) + + " filePhysicalSize=" + toString( filePhysicalSize ) ); } - /// Check indexPhysicalOffset is in bounds + // Check indexPhysicalOffset is in bounds if ( filePhysicalSize > 0 && indexPhysicalOffset >= filePhysicalSize ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_CV_HEADER, "indexPhysicalOffset=" + toString( indexPhysicalOffset ) + - " filePhysicalSize=" + toString( filePhysicalSize ) ); + throw E57_EXCEPTION2( ErrorBadCVHeader, + "indexPhysicalOffset=" + toString( indexPhysicalOffset ) + + " filePhysicalSize=" + toString( filePhysicalSize ) ); } } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void CompressedVectorSectionHeader::dump( int indent, std::ostream &os ) const { - os << space( indent ) << "sectionId: " << static_cast( sectionId ) << std::endl; + os << space( indent ) << "sectionId: " << static_cast( sectionId ) + << std::endl; os << space( indent ) << "sectionLogicalLength: " << sectionLogicalLength << std::endl; os << space( indent ) << "dataPhysicalOffset: " << dataPhysicalOffset << std::endl; os << space( indent ) << "indexPhysicalOffset: " << indexPhysicalOffset << std::endl; diff --git a/src/3rdParty/libE57Format/src/SectionHeaders.h b/src/3rdParty/libE57Format/src/SectionHeaders.h index 2b248d0200a7a..ceb1b30c114f5 100644 --- a/src/3rdParty/libE57Format/src/SectionHeaders.h +++ b/src/3rdParty/libE57Format/src/SectionHeaders.h @@ -43,8 +43,8 @@ namespace e57 uint8_t reserved1[7] = {}; // must be zero uint64_t sectionLogicalLength = 0; // byte length of whole section -#ifdef E57_DEBUG - void dump( int indent = 0, std::ostream &os = std::cout ); +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT + void dump( int indent = 0, std::ostream &os = std::cout ) const; #endif }; @@ -58,9 +58,10 @@ namespace e57 uint64_t indexPhysicalOffset = 0; // offset of first index packet CompressedVectorSectionHeader(); + void verify( uint64_t filePhysicalSize = 0 ); -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const; #endif }; diff --git a/src/3rdParty/libE57Format/src/SourceDestBuffer.cpp b/src/3rdParty/libE57Format/src/SourceDestBuffer.cpp new file mode 100644 index 0000000000000..e23e811535863 --- /dev/null +++ b/src/3rdParty/libE57Format/src/SourceDestBuffer.cpp @@ -0,0 +1,478 @@ +/* + * SourceDestBuffer.cpp - implementation of public functions of the SourceDestBuffer class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file SourceDestBuffer.cpp + +#include "SourceDestBufferImpl.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/// @brief Check whether SourceDestBuffer class invariant is true +void SourceDestBuffer::checkInvariant( bool /*doRecurse*/ ) const +{ + // Stride must be >= a memory type dependent value + const size_t min_stride = []( MemoryRepresentation inRep ) -> size_t { + switch ( inRep ) + { + case Bool: + case Int8: + case UInt8: + return 1; + + case Int16: + case UInt16: + return 2; + + case Int32: + case UInt32: + case Real32: + return 4; + + case Int64: + case Real64: + return 8; + + case UString: + return sizeof( ustring ); + + default: + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + }( memoryRepresentation() ); + + if ( stride() < min_stride ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } +} + +/*! +@class e57::SourceDestBuffer + +@brief A memory buffer to transfer data to/from a CompressedVectorNode in a block. + +@details +The SourceDestBuffer is an encapsulation of a buffer in memory that will transfer data to/from a +field in a CompressedVectorNode. The API user is responsible for creating the actual memory buffer, +describing it correctly to the API, making sure it exists during the transfer period, and destroying +it after the transfer is complete. Additionally, the SourceDestBuffer has information that specifies +the connection to the CompressedVectorNode field (i.e. the field's path name in the prototype). + +The type of buffer element may be an assortment of built-in C++ memory types. There are all +combinations of signed/unsigned and 8/16/32/64 bit integers (except unsigned 64bit integer, which is +not supported in the ASTM standard), bool, float, double, as well as a vector of variable length +unicode strings. The compiler selects the appropriate constructor automatically based on the type of +the buffer array. However, the API user is responsible for reporting the correct length and stride +options (otherwise unspecified behavior can occur). + +The connection of the SourceDestBuffer to a CompressedVectorNode field is established by specifying +the pathName. There are several options to this connection: doConversion and doScaling, which are +described in the constructor documentation. + +@section sourcedestbuffer_invariant Class Invariant +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude SourceDestBuffer.cpp +@skip void SourceDestBuffer::checkInvariant +@until ^} + +@see Node +*/ + +/*! +@brief Designate buffers to transfer data to/from a CompressedVectorNode in a block. + +@param [in] destImageFile The ImageFile where the new node will eventually be stored. +@param [in] pathName The pathname of the field in CompressedVectorNode that will transfer data +to/from. +@param [in] b The caller allocated memory buffer. +@param [in] capacity The total number of memory elements in buffer @a b. +@param [in] doConversion Will a conversion be attempted between memory and ImageFile +representations. +@param [in] doScaling In a ScaledInteger field, do memory elements hold scaled values, if false they +hold raw values. +@param [in] stride The number of bytes between memory elements. If zero, defaults to sizeof memory +element. + +@details +This overloaded form of the SourceDestBuffer constructor declares a buffer @a b to be the +source/destination of a transfer of values stored in a CompressedVectorNode. + +The @a pathName will be used to identify a Node in the prototype that will get/receive data from +this buffer. The @a pathName may be an absolute path name (e.g. "/cartesianX") or a path name +relative to the root of the prototype (i.e. the absolute path name without the leading "/", for +example: "cartesianX"). + +The type of @a b is used to determine the MemoryRepresentation of the SourceDestBuffer. The buffer +@a b may be used for multiple block transfers. See discussions of operation of SourceDestBuffer +attributes in SourceDestBuffer::memoryRepresentation, SourceDestBuffer::capacity, +SourceDestBuffer::doConversion, and SourceDestBuffer::doScaling, and SourceDestBuffer::stride. + +The API user is responsible for ensuring that the lifetime of the @a b memory buffer exceeds the +time that it is used in transfers (i.e. the E57 Foundation Implementation cannot detect that the +buffer been destroyed). + +The @a capacity must match the capacity of all other SourceDestBuffers that will participate in a +transfer with a CompressedVectorNode. + +@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be true). +@pre The stride must be >= sizeof(*b) + +@throw ::ErrorBadAPIArgument +@throw ::ErrorBadPathName +@throw ::ErrorBadBuffer +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ImageFile::reader, ImageFile::writer, +CompressedVectorReader::read(std::vector&), +CompressedVectorWriter::write(std::vector&) +*/ +SourceDestBuffer::SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + int8_t *b, const size_t capacity, bool doConversion, + bool doScaling, size_t stride ) : + impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, + doScaling ) ) +{ + impl_->setTypeInfo( b, stride ); +} + +/// @overload +SourceDestBuffer::SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + uint8_t *b, const size_t capacity, bool doConversion, + bool doScaling, size_t stride ) : + impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, + doScaling ) ) +{ + impl_->setTypeInfo( b, stride ); +} + +/// @overload +SourceDestBuffer::SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + int16_t *b, const size_t capacity, bool doConversion, + bool doScaling, size_t stride ) : + impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, + doScaling ) ) +{ + impl_->setTypeInfo( b, stride ); +} + +/// @overload +SourceDestBuffer::SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + uint16_t *b, const size_t capacity, bool doConversion, + bool doScaling, size_t stride ) : + impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, + doScaling ) ) +{ + impl_->setTypeInfo( b, stride ); +} + +/// @overload +SourceDestBuffer::SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + int32_t *b, const size_t capacity, bool doConversion, + bool doScaling, size_t stride ) : + impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, + doScaling ) ) +{ + impl_->setTypeInfo( b, stride ); +} + +/// @overload +SourceDestBuffer::SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + uint32_t *b, const size_t capacity, bool doConversion, + bool doScaling, size_t stride ) : + impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, + doScaling ) ) +{ + impl_->setTypeInfo( b, stride ); +} + +/// @overload +SourceDestBuffer::SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + int64_t *b, const size_t capacity, bool doConversion, + bool doScaling, size_t stride ) : + impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, + doScaling ) ) +{ + impl_->setTypeInfo( b, stride ); +} + +/// @overload +SourceDestBuffer::SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + bool *b, const size_t capacity, bool doConversion, + bool doScaling, size_t stride ) : + impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, + doScaling ) ) +{ + impl_->setTypeInfo( b, stride ); +} + +/// @overload +SourceDestBuffer::SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + float *b, const size_t capacity, bool doConversion, + bool doScaling, size_t stride ) : + impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, + doScaling ) ) +{ + impl_->setTypeInfo( b, stride ); +} + +/// @overload +SourceDestBuffer::SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + double *b, const size_t capacity, bool doConversion, + bool doScaling, size_t stride ) : + impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, capacity, doConversion, + doScaling ) ) +{ + impl_->setTypeInfo( b, stride ); +} + +/*! +@brief Designate vector of strings to transfer data to/from a CompressedVector as a block. + +@param [in] destImageFile The ImageFile where the new node will eventually be stored. +@param [in] pathName The pathname of the field in CompressedVectorNode that will transfer data +to/from. +@param [in] b The caller created vector of ustrings to transfer from/to. + +@details +This overloaded form of the SourceDestBuffer constructor declares a vector to be the +source/destination of a transfer of StringNode values stored in a CompressedVectorNode. + +The @a pathName will be used to identify a Node in the prototype that will get/receive data from +this buffer. The @a pathName may be an absolute path name (e.g. "/cartesianX") or a path name +relative to the root of the prototype (i.e. the absolute path name without the leading "/", for +example: "cartesianX"). + +The @a b->size() must match capacity of all other SourceDestBuffers that will participate in a +transfer with a CompressedVectorNode (string or any other type of buffer). In a read into the +SourceDestBuffer, the previous contents of the strings in the vector are lost, and the memory space +is potentially freed. The @a b->size() of the vector will not be changed. It is an error to request +a read/write of more records that @a b->size() (just as it would be for buffers of integer types). +The API user is responsible for ensuring that the lifetime of the @a b vector exceeds the time that +it is used in transfers (i.e. the E57 Foundation Implementation cannot detect that the buffer been +destroyed). + +@pre b.size() must be > 0. +@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be true). + +@throw ::ErrorBadAPIArgument +@throw ::ErrorBadPathName +@throw ::ErrorBadBuffer +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see SourceDestBuffer::doConversion for discussion on representations compatible with string +SourceDestBuffers. +*/ +SourceDestBuffer::SourceDestBuffer( const ImageFile &destImageFile, const ustring &pathName, + std::vector *b ) : + impl_( new SourceDestBufferImpl( destImageFile.impl(), pathName, b ) ) +{ +} + +/*! +@brief Get path name in prototype that this SourceDestBuffer will transfer data to/from. + +@details +The prototype of a CompressedVectorNode describes the fields that are in each record. This function +returns the path name of the node in the prototype tree that this SourceDestBuffer will write/read. +The correctness of this path name is checked when this SourceDestBuffer is associated with a +CompressedVectorNode (either in CompressedVectorNode::writer, +CompressedVectorWriter::write(std::vector&, unsigned), +CompressedVectorNode::reader, CompressedVectorReader::read(std::vector&)). + +@post No visible state is modified. + +@return Path name in prototype that this SourceDestBuffer will transfer data to/from. + +@throw ::ErrorInternal All objects in undocumented state + +@see CompressedVector, CompressedVectorNode::prototype +*/ +ustring SourceDestBuffer::pathName() const +{ + return impl_->pathName(); +} + +/*! +@brief Get memory representation of the elements in this SourceDestBuffer. + +@details +The memory representation is deduced from which overloaded SourceDestBuffer constructor was used. +The memory representation is independent of the type and minimum/maximum bounds of the node in the +prototype that the SourceDestBuffer will transfer to/from. However, some combinations will result in +an error if doConversion is not requested (e.g. ::Int16 and FloatNode). + +Some combinations risk an error occurring during a write, if a value is too large (e.g. writing an +::Int16 memory representation to an IntegerNode with minimum=-1024 maximum=1023). Some combinations +risk an error occurring during a read, if a value is too large (e.g. reading an IntegerNode with +minimum=-1024 maximum=1023 int an ::Int8 memory representation). Some combinations are never +possible (e.g. ::Int16 and StringNode). + +@post No visible state is modified. + +@return Memory representation of the elements in buffer. + +@throw ::ErrorInternal All objects in undocumented state + +@see MemoryRepresentation, NodeType +*/ +MemoryRepresentation SourceDestBuffer::memoryRepresentation() const +{ + return impl_->memoryRepresentation(); +} + +/*! +@brief Get total capacity of buffer. + +@details +The API programmer is responsible for correctly specifying the length of a buffer. This function +returns that declared length. If the length is incorrect (in particular, too long) memory may be +corrupted or erroneous values written. + +@post No visible state is modified. + +@return Total capacity of buffer. + +@throw ::ErrorInternal All objects in undocumented state +*/ +size_t SourceDestBuffer::capacity() const +{ + return impl_->capacity(); +} + +/*! +@brief Get whether conversions will be performed to match the memory type of buffer. + +@details +The API user must explicitly request conversion between basic representation groups in memory and on +the disk. The four basic representation groups are: integer, boolean, floating point, and string. +There is no distinction between integer and boolean groups on the disk (they both use IntegerNode). +A explicit request for conversion between single and double precision floating point representations +is not required. + +The most useful conversion is between integer and floating point representation groups. Conversion +from integer to floating point representations cannot result in an overflow, and is usually +loss-less (except for extremely large integers). Conversion from floating point to integer +representations can result in an overflow, and can be lossy. + +Conversion between any of the integer, boolean, and floating point representation groups is +supported. No conversion from the string to any other representation group is possible. Missing or +unsupported conversions are detected when the first transfer is attempted (i.e. not when the +CompressedVectorReader or CompressedVectorWriter is created). + +@post No visible state is modified. + +@return true if conversions will be performed to match the memory type of buffer. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state +*/ +bool SourceDestBuffer::doConversion() const +{ + return impl_->doConversion(); +} + +/*! +@brief Get whether scaling will be performed for ScaledIntegerNode transfers. + +@details +The doScaling option only applies to ScaledIntegerNodes stored in a CompressedVectorNode on the disk +(it is ignored if a ScaledIntegerNode is not involved). + +As a convenience, an E57 Foundation Implementation can perform scaling of data so that the API user +can manipulate scaledValues rather than rawValues. For a reader, the scaling process is: scaledValue += (rawValue * scale) + offset. For a writer, the scaling process is reversed: rawValue = +(scaledValue - offset) / scale. The result performing a scaling in a reader (or "unscaling" in a +writer) is always a floating point number. This floating point number may have to be converted to be +compatible with the destination representation. If the destination representation is not floating +point, there is a risk of violating declared min/max bounds. Because of this risk, it is recommended +that scaling only be requested for reading scaledValues from ScaledIntegerNodes into floating point +numbers in memory. + +It is also possible (and perhaps safest of all) to never request that scaling be performed, and +always deal with rawValues outside the API. Note this does not mean that ScaledIntegerNodes should +be avoided. ScaledIntegerNodes are essential for encoding numeric data with fractional parts in +CompressedVectorNodes. Because the ASTM E57 format recommends that SI units without prefix be used +(i.e. meters, not milli-meters or micro-furlongs), almost every measured value will have a +fractional part. + +@post No visible state is modified. + +@return true if scaling will be performed for ScaledInteger transfers. + +@throw ::ErrorInternal All objects in undocumented state + +@see ScaledIntegerNode +*/ +bool SourceDestBuffer::doScaling() const +{ + return impl_->doScaling(); +} + +/*! +@brief Get number of bytes between consecutive memory elements in buffer + +@details +Elements in a memory buffer do not have to be consecutive. They can also be spaced at regular +intervals. This allows a value to be picked out of an array of C++ structures (the stride would be +the size of the structure). In the case that the element values are stored consecutively in memory, +the stride equals the size of the memory representation of the element. + +@post No visible state is modified. + +@return Number of bytes between consecutive memory elements in buffer +*/ +size_t SourceDestBuffer::stride() const +{ + return impl_->stride(); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void SourceDestBuffer::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void SourceDestBuffer::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif diff --git a/src/3rdParty/libE57Format/src/SourceDestBufferImpl.cpp b/src/3rdParty/libE57Format/src/SourceDestBufferImpl.cpp index 010a27296c764..c534e30642fa9 100644 --- a/src/3rdParty/libE57Format/src/SourceDestBufferImpl.cpp +++ b/src/3rdParty/libE57Format/src/SourceDestBufferImpl.cpp @@ -29,13 +29,16 @@ #include "ImageFileImpl.h" #include "SourceDestBufferImpl.h" +#include "StringFunctions.h" using namespace e57; -SourceDestBufferImpl::SourceDestBufferImpl( ImageFileImplWeakPtr destImageFile, const ustring &pathName, - const size_t capacity, bool doConversion, bool doScaling ) : +SourceDestBufferImpl::SourceDestBufferImpl( ImageFileImplWeakPtr destImageFile, + const ustring &pathName, const size_t capacity, + bool doConversion, bool doScaling ) : destImageFile_( destImageFile ), - pathName_( pathName ), capacity_( capacity ), doConversion_( doConversion ), doScaling_( doScaling ) + pathName_( pathName ), memoryRepresentation_( Int32 ), capacity_( capacity ), + doConversion_( doConversion ), doScaling_( doScaling ) { } @@ -51,43 +54,43 @@ template void SourceDestBufferImpl::setTypeInfo( T *base, size_t st // representation if ( std::is_same::value ) { - memoryRepresentation_ = E57_INT8; + memoryRepresentation_ = Int8; } else if ( std::is_same::value ) { - memoryRepresentation_ = E57_UINT8; + memoryRepresentation_ = UInt8; } else if ( std::is_same::value ) { - memoryRepresentation_ = E57_INT16; + memoryRepresentation_ = Int16; } else if ( std::is_same::value ) { - memoryRepresentation_ = E57_UINT16; + memoryRepresentation_ = UInt16; } else if ( std::is_same::value ) { - memoryRepresentation_ = E57_INT32; + memoryRepresentation_ = Int32; } else if ( std::is_same::value ) { - memoryRepresentation_ = E57_UINT32; + memoryRepresentation_ = UInt32; } else if ( std::is_same::value ) { - memoryRepresentation_ = E57_INT64; + memoryRepresentation_ = Int64; } else if ( std::is_same::value ) { - memoryRepresentation_ = E57_BOOL; + memoryRepresentation_ = Bool; } else if ( std::is_same::value ) { - memoryRepresentation_ = E57_REAL32; + memoryRepresentation_ = Real32; } else if ( std::is_same::value ) { - memoryRepresentation_ = E57_REAL64; + memoryRepresentation_ = Real64; } checkState_(); @@ -104,17 +107,17 @@ template void SourceDestBufferImpl::setTypeInfo( bool *base, size_t stride template void SourceDestBufferImpl::setTypeInfo( float *base, size_t stride ); template void SourceDestBufferImpl::setTypeInfo( double *base, size_t stride ); -SourceDestBufferImpl::SourceDestBufferImpl( ImageFileImplWeakPtr destImageFile, const ustring &pathName, - std::vector *b ) : +SourceDestBufferImpl::SourceDestBufferImpl( ImageFileImplWeakPtr destImageFile, + const ustring &pathName, std::vector *b ) : destImageFile_( destImageFile ), - pathName_( pathName ), memoryRepresentation_( E57_USTRING ), ustrings_( b ) + pathName_( pathName ), memoryRepresentation_( UString ), ustrings_( b ) { /// don't checkImageFileOpen, checkState_ will do it /// Set capacity_ after testing that b is OK - if ( !b ) + if ( b == nullptr ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_BUFFER, "sdbuf.pathName=" + pathName ); + throw E57_EXCEPTION2( ErrorBadBuffer, "sdbuf.pathName=" + pathName ); } capacity_ = b->size(); @@ -136,7 +139,7 @@ template void SourceDestBufferImpl::_setNextReal( T inValue ) /// Verify have room if ( nextIndex_ >= capacity_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } /// Calc start of memory location, index into buffer using stride_ (the @@ -145,108 +148,108 @@ template void SourceDestBufferImpl::_setNextReal( T inValue ) switch ( memoryRepresentation_ ) { - case E57_INT8: + case Int8: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } //??? fault if get special value: NaN, NegInf... (all other ints below // too) - if ( inValue < E57_INT8_MIN || E57_INT8_MAX < inValue ) + if ( inValue < INT8_MIN || INT8_MAX < inValue ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( inValue ) ); } *reinterpret_cast( p ) = static_cast( inValue ); break; - case E57_UINT8: + case UInt8: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } - if ( inValue < E57_UINT8_MIN || E57_UINT8_MAX < inValue ) + if ( inValue < UINT8_MIN || UINT8_MAX < inValue ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( inValue ) ); } *reinterpret_cast( p ) = static_cast( inValue ); break; - case E57_INT16: + case Int16: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } - if ( inValue < E57_INT16_MIN || E57_INT16_MAX < inValue ) + if ( inValue < INT16_MIN || INT16_MAX < inValue ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( inValue ) ); } *reinterpret_cast( p ) = static_cast( inValue ); break; - case E57_UINT16: + case UInt16: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } - if ( inValue < E57_UINT16_MIN || E57_UINT16_MAX < inValue ) + if ( inValue < UINT16_MIN || UINT16_MAX < inValue ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( inValue ) ); } *reinterpret_cast( p ) = static_cast( inValue ); break; - case E57_INT32: + case Int32: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } - if ( inValue < E57_INT32_MIN || E57_INT32_MAX < inValue ) + if ( inValue < INT32_MIN || ( inValue > static_cast( INT32_MAX ) ) ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( inValue ) ); } *reinterpret_cast( p ) = static_cast( inValue ); break; - case E57_UINT32: + case UInt32: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } - if ( inValue < E57_UINT32_MIN || E57_UINT32_MAX < inValue ) + if ( inValue < UINT32_MIN || ( inValue > ( static_cast( UINT32_MAX ) ) ) ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( inValue ) ); } *reinterpret_cast( p ) = static_cast( inValue ); break; - case E57_INT64: + case Int64: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } - if ( inValue < E57_INT64_MIN || E57_INT64_MAX < inValue ) + if ( inValue < INT64_MIN || ( inValue > ( static_cast( INT64_MAX ) ) ) ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( inValue ) ); } *reinterpret_cast( p ) = static_cast( inValue ); break; - case E57_BOOL: + case Bool: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } *reinterpret_cast( p ) = ( inValue ? false : true ); break; - case E57_REAL32: + case Real32: if ( std::is_same::value ) { /// Does this count as conversion? It loses information. /// Check for really large exponents that can't fit in a single /// precision - if ( inValue < E57_DOUBLE_MIN || E57_DOUBLE_MAX < inValue ) + if ( inValue < DOUBLE_MIN || DOUBLE_MAX < inValue ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( inValue ) ); } *reinterpret_cast( p ) = static_cast( inValue ); @@ -254,7 +257,8 @@ template void SourceDestBufferImpl::_setNextReal( T inValue ) else { #ifdef _MSC_VER - // MSVC is not smart enough to realize 'inValue' cannot be a double here, so disable warning + // MSVC is not smart enough to realize 'inValue' cannot be a double here, so disable + // warning #pragma warning( disable : 4244 ) *reinterpret_cast( p ) = inValue; #pragma warning( default : 4244 ) @@ -263,12 +267,12 @@ template void SourceDestBufferImpl::_setNextReal( T inValue ) #endif } break; - case E57_REAL64: + case Real64: //??? does this count as a conversion? *reinterpret_cast( p ) = static_cast( inValue ); break; - case E57_USTRING: - throw E57_EXCEPTION2( E57_ERROR_EXPECTING_NUMERIC, "pathName=" + pathName_ ); + case UString: + throw E57_EXCEPTION2( ErrorExpectingNumeric, "pathName=" + pathName_ ); } nextIndex_++; @@ -281,7 +285,7 @@ void SourceDestBufferImpl::checkState_() const ImageFileImplSharedPtr destImageFile( destImageFile_ ); if ( !destImageFile->isOpen() ) { - throw E57_EXCEPTION2( E57_ERROR_IMAGEFILE_NOT_OPEN, "fileName=" + destImageFile->fileName() ); + throw E57_EXCEPTION2( ErrorImageFileNotOpen, "fileName=" + destImageFile->fileName() ); } /// Check pathName is well formed (can't verify path is defined until @@ -289,24 +293,24 @@ void SourceDestBufferImpl::checkState_() const ImageFileImplSharedPtr imf( destImageFile_ ); imf->pathNameCheckWellFormed( pathName_ ); - if ( memoryRepresentation_ != E57_USTRING ) + if ( memoryRepresentation_ != UString ) { - if ( !base_ ) + if ( base_ == nullptr ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_BUFFER, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorBadBuffer, "pathName=" + pathName_ ); } if ( stride_ == 0 ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_BUFFER, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorBadBuffer, "pathName=" + pathName_ ); } //??? check base alignment, depending on CPU type //??? check if stride too small, positive or negative } else { - if ( !ustrings_ ) + if ( ustrings_ == nullptr ) { - throw E57_EXCEPTION2( E57_ERROR_BAD_BUFFER, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorBadBuffer, "pathName=" + pathName_ ); } } } @@ -318,7 +322,7 @@ int64_t SourceDestBufferImpl::getNextInt64() /// Verify index is within bounds if ( nextIndex_ >= capacity_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } /// Fetch value from source buffer. @@ -327,55 +331,55 @@ int64_t SourceDestBufferImpl::getNextInt64() int64_t value; switch ( memoryRepresentation_ ) { - case E57_INT8: + case Int8: value = static_cast( *reinterpret_cast( p ) ); break; - case E57_UINT8: + case UInt8: value = static_cast( *reinterpret_cast( p ) ); break; - case E57_INT16: + case Int16: value = static_cast( *reinterpret_cast( p ) ); break; - case E57_UINT16: + case UInt16: value = static_cast( *reinterpret_cast( p ) ); break; - case E57_INT32: + case Int32: value = static_cast( *reinterpret_cast( p ) ); break; - case E57_UINT32: + case UInt32: value = static_cast( *reinterpret_cast( p ) ); break; - case E57_INT64: + case Int64: value = *reinterpret_cast( p ); break; - case E57_BOOL: + case Bool: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } /// Convert bool to 0/1, all non-zero values map to 1.0 value = ( *reinterpret_cast( p ) ) ? 1 : 0; break; - case E57_REAL32: + case Real32: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } //??? fault if get special value: NaN, NegInf... value = static_cast( *reinterpret_cast( p ) ); break; - case E57_REAL64: + case Real64: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } //??? fault if get special value: NaN, NegInf... value = static_cast( *reinterpret_cast( p ) ); break; - case E57_USTRING: - throw E57_EXCEPTION2( E57_ERROR_EXPECTING_NUMERIC, "pathName=" + pathName_ ); + case UString: + throw E57_EXCEPTION2( ErrorExpectingNumeric, "pathName=" + pathName_ ); default: - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } nextIndex_++; return ( value ); @@ -400,13 +404,13 @@ int64_t SourceDestBufferImpl::getNextInt64( double scale, double offset ) /// Double check non-zero scale. Going to divide by it below. if ( scale == 0 ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } /// Verify index is within bounds if ( nextIndex_ >= capacity_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } /// Fetch value from source buffer. @@ -415,42 +419,42 @@ int64_t SourceDestBufferImpl::getNextInt64( double scale, double offset ) double doubleRawValue; switch ( memoryRepresentation_ ) { - case E57_INT8: + case Int8: /// Calc (x-offset)/scale rounded to nearest integer, but keep in /// floating point until sure is in bounds doubleRawValue = floor( ( *reinterpret_cast( p ) - offset ) / scale + 0.5 ); break; - case E57_UINT8: + case UInt8: /// Calc (x-offset)/scale rounded to nearest integer, but keep in /// floating point until sure is in bounds doubleRawValue = floor( ( *reinterpret_cast( p ) - offset ) / scale + 0.5 ); break; - case E57_INT16: + case Int16: /// Calc (x-offset)/scale rounded to nearest integer, but keep in /// floating point until sure is in bounds doubleRawValue = floor( ( *reinterpret_cast( p ) - offset ) / scale + 0.5 ); break; - case E57_UINT16: + case UInt16: /// Calc (x-offset)/scale rounded to nearest integer, but keep in /// floating point until sure is in bounds doubleRawValue = floor( ( *reinterpret_cast( p ) - offset ) / scale + 0.5 ); break; - case E57_INT32: + case Int32: /// Calc (x-offset)/scale rounded to nearest integer, but keep in /// floating point until sure is in bounds doubleRawValue = floor( ( *reinterpret_cast( p ) - offset ) / scale + 0.5 ); break; - case E57_UINT32: + case UInt32: /// Calc (x-offset)/scale rounded to nearest integer, but keep in /// floating point until sure is in bounds doubleRawValue = floor( ( *reinterpret_cast( p ) - offset ) / scale + 0.5 ); break; - case E57_INT64: + case Int64: /// Calc (x-offset)/scale rounded to nearest integer, but keep in /// floating point until sure is in bounds doubleRawValue = floor( ( *reinterpret_cast( p ) - offset ) / scale + 0.5 ); break; - case E57_BOOL: + case Bool: if ( *reinterpret_cast( p ) ) { doubleRawValue = floor( ( 1 - offset ) / scale + 0.5 ); @@ -460,10 +464,10 @@ int64_t SourceDestBufferImpl::getNextInt64( double scale, double offset ) doubleRawValue = floor( ( 0 - offset ) / scale + 0.5 ); } break; - case E57_REAL32: + case Real32: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } //??? fault if get special value: NaN, NegInf... @@ -471,10 +475,10 @@ int64_t SourceDestBufferImpl::getNextInt64( double scale, double offset ) /// floating point until sure is in bounds doubleRawValue = floor( ( *reinterpret_cast( p ) - offset ) / scale + 0.5 ); break; - case E57_REAL64: + case Real64: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } //??? fault if get special value: NaN, NegInf... @@ -482,15 +486,16 @@ int64_t SourceDestBufferImpl::getNextInt64( double scale, double offset ) /// floating point until sure is in bounds doubleRawValue = floor( ( *reinterpret_cast( p ) - offset ) / scale + 0.5 ); break; - case E57_USTRING: - throw E57_EXCEPTION2( E57_ERROR_EXPECTING_NUMERIC, "pathName=" + pathName_ ); + case UString: + throw E57_EXCEPTION2( ErrorExpectingNumeric, "pathName=" + pathName_ ); default: - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } + /// Make sure that value is representable in an int64_t - if ( doubleRawValue < E57_INT64_MIN || E57_INT64_MAX < doubleRawValue ) + if ( doubleRawValue < INT64_MIN || ( doubleRawValue > ( static_cast( INT64_MAX ) ) ) ) { - throw E57_EXCEPTION2( E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorScaledValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( doubleRawValue ) ); } @@ -507,7 +512,7 @@ float SourceDestBufferImpl::getNextFloat() /// Verify index is within bounds if ( nextIndex_ >= capacity_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } /// Fetch value from source buffer. @@ -516,85 +521,86 @@ float SourceDestBufferImpl::getNextFloat() float value; switch ( memoryRepresentation_ ) { - case E57_INT8: + case Int8: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_UINT8: + case UInt8: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_INT16: + case Int16: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_UINT16: + case UInt16: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_INT32: + case Int32: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_UINT32: + case UInt32: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_INT64: + case Int64: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_BOOL: + case Bool: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } /// Convert bool to 0/1, all non-zero values map to 1.0 value = ( *reinterpret_cast( p ) ) ? 1.0F : 0.0F; break; - case E57_REAL32: + case Real32: value = *reinterpret_cast( p ); break; - case E57_REAL64: + case Real64: { /// Check that exponent of user's value is not too large for single /// precision number in file. double d = *reinterpret_cast( p ); ///??? silently limit here? - if ( d < E57_DOUBLE_MIN || E57_DOUBLE_MAX < d ) + if ( d < DOUBLE_MIN || DOUBLE_MAX < d ) { - throw E57_EXCEPTION2( E57_ERROR_REAL64_TOO_LARGE, "pathName=" + pathName_ + " value=" + toString( d ) ); + throw E57_EXCEPTION2( ErrorReal64TooLarge, + "pathName=" + pathName_ + " value=" + toString( d ) ); } value = static_cast( d ); break; } - case E57_USTRING: - throw E57_EXCEPTION2( E57_ERROR_EXPECTING_NUMERIC, "pathName=" + pathName_ ); + case UString: + throw E57_EXCEPTION2( ErrorExpectingNumeric, "pathName=" + pathName_ ); default: - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } nextIndex_++; return ( value ); @@ -607,7 +613,7 @@ double SourceDestBufferImpl::getNextDouble() /// Verify index is within bounds if ( nextIndex_ >= capacity_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } /// Fetch value from source buffer. @@ -616,73 +622,73 @@ double SourceDestBufferImpl::getNextDouble() double value; switch ( memoryRepresentation_ ) { - case E57_INT8: + case Int8: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_UINT8: + case UInt8: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_INT16: + case Int16: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_UINT16: + case UInt16: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_INT32: + case Int32: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_UINT32: + case UInt32: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_INT64: + case Int64: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } value = static_cast( *reinterpret_cast( p ) ); break; - case E57_BOOL: + case Bool: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } /// Convert bool to 0/1, all non-zero values map to 1.0 value = ( *reinterpret_cast( p ) ) ? 1.0 : 0.0; break; - case E57_REAL32: + case Real32: value = static_cast( *reinterpret_cast( p ) ); break; - case E57_REAL64: + case Real64: value = *reinterpret_cast( p ); break; - case E57_USTRING: - throw E57_EXCEPTION2( E57_ERROR_EXPECTING_NUMERIC, "pathName=" + pathName_ ); + case UString: + throw E57_EXCEPTION2( ErrorExpectingNumeric, "pathName=" + pathName_ ); default: - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } nextIndex_++; return ( value ); @@ -693,15 +699,15 @@ ustring SourceDestBufferImpl::getNextString() /// don't checkImageFileOpen /// Check have correct type buffer - if ( memoryRepresentation_ != E57_USTRING ) + if ( memoryRepresentation_ != UString ) { - throw E57_EXCEPTION2( E57_ERROR_EXPECTING_USTRING, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorExpectingUString, "pathName=" + pathName_ ); } /// Verify index is within bounds if ( nextIndex_ >= capacity_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } /// Get ustring from vector @@ -715,7 +721,7 @@ void SourceDestBufferImpl::setNextInt64( int64_t value ) /// Verify have room if ( nextIndex_ >= capacity_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } /// Calc start of memory location, index into buffer using stride_ (the @@ -724,77 +730,77 @@ void SourceDestBufferImpl::setNextInt64( int64_t value ) switch ( memoryRepresentation_ ) { - case E57_INT8: - if ( value < E57_INT8_MIN || E57_INT8_MAX < value ) + case Int8: + if ( value < INT8_MIN || INT8_MAX < value ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( value ) ); } *reinterpret_cast( p ) = static_cast( value ); break; - case E57_UINT8: - if ( value < E57_UINT8_MIN || E57_UINT8_MAX < value ) + case UInt8: + if ( value < UINT8_MIN || UINT8_MAX < value ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( value ) ); } *reinterpret_cast( p ) = static_cast( value ); break; - case E57_INT16: - if ( value < E57_INT16_MIN || E57_INT16_MAX < value ) + case Int16: + if ( value < INT16_MIN || INT16_MAX < value ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( value ) ); } *reinterpret_cast( p ) = static_cast( value ); break; - case E57_UINT16: - if ( value < E57_UINT16_MIN || E57_UINT16_MAX < value ) + case UInt16: + if ( value < UINT16_MIN || UINT16_MAX < value ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( value ) ); } *reinterpret_cast( p ) = static_cast( value ); break; - case E57_INT32: - if ( value < E57_INT32_MIN || E57_INT32_MAX < value ) + case Int32: + if ( value < INT32_MIN || INT32_MAX < value ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( value ) ); } *reinterpret_cast( p ) = static_cast( value ); break; - case E57_UINT32: - if ( value < E57_UINT32_MIN || E57_UINT32_MAX < value ) + case UInt32: + if ( value < UINT32_MIN || UINT32_MAX < value ) { - throw E57_EXCEPTION2( E57_ERROR_VALUE_NOT_REPRESENTABLE, + throw E57_EXCEPTION2( ErrorValueNotRepresentable, "pathName=" + pathName_ + " value=" + toString( value ) ); } *reinterpret_cast( p ) = static_cast( value ); break; - case E57_INT64: + case Int64: *reinterpret_cast( p ) = static_cast( value ); break; - case E57_BOOL: + case Bool: *reinterpret_cast( p ) = ( value ? false : true ); break; - case E57_REAL32: + case Real32: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } //??? very large integers may lose some lowest bits here. error? *reinterpret_cast( p ) = static_cast( value ); break; - case E57_REAL64: + case Real64: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } *reinterpret_cast( p ) = static_cast( value ); break; - case E57_USTRING: - throw E57_EXCEPTION2( E57_ERROR_EXPECTING_NUMERIC, "pathName=" + pathName_ ); + case UString: + throw E57_EXCEPTION2( ErrorExpectingNumeric, "pathName=" + pathName_ ); } nextIndex_++; @@ -820,7 +826,7 @@ void SourceDestBufferImpl::setNextInt64( int64_t value, double scale, double off /// Verify have room if ( nextIndex_ >= capacity_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } /// Calc start of memory location, index into buffer using stride_ (the @@ -829,7 +835,7 @@ void SourceDestBufferImpl::setNextInt64( int64_t value, double scale, double off /// Calc x*scale+offset double scaledValue; - if ( memoryRepresentation_ == E57_REAL32 || memoryRepresentation_ == E57_REAL64 ) + if ( memoryRepresentation_ == Real32 || memoryRepresentation_ == Real64 ) { /// Value will be stored in some floating point rep in user's buffer, so /// keep full resolution here. @@ -845,83 +851,90 @@ void SourceDestBufferImpl::setNextInt64( int64_t value, double scale, double off switch ( memoryRepresentation_ ) { - case E57_INT8: - if ( scaledValue < E57_INT8_MIN || E57_INT8_MAX < scaledValue ) + case Int8: + if ( scaledValue < INT8_MIN || INT8_MAX < scaledValue ) { - throw E57_EXCEPTION2( E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE, - "pathName=" + pathName_ + " scaledValue=" + toString( scaledValue ) ); + throw E57_EXCEPTION2( ErrorScaledValueNotRepresentable, + "pathName=" + pathName_ + + " scaledValue=" + toString( scaledValue ) ); } *reinterpret_cast( p ) = static_cast( scaledValue ); break; - case E57_UINT8: - if ( scaledValue < E57_UINT8_MIN || E57_UINT8_MAX < scaledValue ) + case UInt8: + if ( scaledValue < UINT8_MIN || UINT8_MAX < scaledValue ) { - throw E57_EXCEPTION2( E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE, - "pathName=" + pathName_ + " scaledValue=" + toString( scaledValue ) ); + throw E57_EXCEPTION2( ErrorScaledValueNotRepresentable, + "pathName=" + pathName_ + + " scaledValue=" + toString( scaledValue ) ); } *reinterpret_cast( p ) = static_cast( scaledValue ); break; - case E57_INT16: - if ( scaledValue < E57_INT16_MIN || E57_INT16_MAX < scaledValue ) + case Int16: + if ( scaledValue < INT16_MIN || INT16_MAX < scaledValue ) { - throw E57_EXCEPTION2( E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE, - "pathName=" + pathName_ + " scaledValue=" + toString( scaledValue ) ); + throw E57_EXCEPTION2( ErrorScaledValueNotRepresentable, + "pathName=" + pathName_ + + " scaledValue=" + toString( scaledValue ) ); } *reinterpret_cast( p ) = static_cast( scaledValue ); break; - case E57_UINT16: - if ( scaledValue < E57_UINT16_MIN || E57_UINT16_MAX < scaledValue ) + case UInt16: + if ( scaledValue < UINT16_MIN || UINT16_MAX < scaledValue ) { - throw E57_EXCEPTION2( E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE, - "pathName=" + pathName_ + " scaledValue=" + toString( scaledValue ) ); + throw E57_EXCEPTION2( ErrorScaledValueNotRepresentable, + "pathName=" + pathName_ + + " scaledValue=" + toString( scaledValue ) ); } *reinterpret_cast( p ) = static_cast( scaledValue ); break; - case E57_INT32: - if ( scaledValue < E57_INT32_MIN || E57_INT32_MAX < scaledValue ) + case Int32: + if ( scaledValue < INT32_MIN || INT32_MAX < scaledValue ) { - throw E57_EXCEPTION2( E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE, - "pathName=" + pathName_ + " scaledValue=" + toString( scaledValue ) ); + throw E57_EXCEPTION2( ErrorScaledValueNotRepresentable, + "pathName=" + pathName_ + + " scaledValue=" + toString( scaledValue ) ); } *reinterpret_cast( p ) = static_cast( scaledValue ); break; - case E57_UINT32: - if ( scaledValue < E57_UINT32_MIN || E57_UINT32_MAX < scaledValue ) + case UInt32: + if ( scaledValue < UINT32_MIN || UINT32_MAX < scaledValue ) { - throw E57_EXCEPTION2( E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE, - "pathName=" + pathName_ + " scaledValue=" + toString( scaledValue ) ); + throw E57_EXCEPTION2( ErrorScaledValueNotRepresentable, + "pathName=" + pathName_ + + " scaledValue=" + toString( scaledValue ) ); } *reinterpret_cast( p ) = static_cast( scaledValue ); break; - case E57_INT64: + case Int64: *reinterpret_cast( p ) = static_cast( scaledValue ); break; - case E57_BOOL: + case Bool: *reinterpret_cast( p ) = ( scaledValue ? false : true ); break; - case E57_REAL32: + case Real32: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } /// Check that exponent of result is not too big for single precision /// float - if ( scaledValue < E57_DOUBLE_MIN || E57_DOUBLE_MAX < scaledValue ) + if ( scaledValue < DOUBLE_MIN || DOUBLE_MAX < scaledValue ) { - throw E57_EXCEPTION2( E57_ERROR_SCALED_VALUE_NOT_REPRESENTABLE, - "pathName=" + pathName_ + " scaledValue=" + toString( scaledValue ) ); + throw E57_EXCEPTION2( ErrorScaledValueNotRepresentable, + "pathName=" + pathName_ + + " scaledValue=" + toString( scaledValue ) ); } *reinterpret_cast( p ) = static_cast( scaledValue ); break; - case E57_REAL64: + case Real64: if ( !doConversion_ ) { - throw E57_EXCEPTION2( E57_ERROR_CONVERSION_REQUIRED, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorConversionRequired, "pathName=" + pathName_ ); } *reinterpret_cast( p ) = scaledValue; break; - case E57_USTRING: - throw E57_EXCEPTION2( E57_ERROR_EXPECTING_NUMERIC, "pathName=" + pathName_ ); + case UString: + throw E57_EXCEPTION2( ErrorExpectingNumeric, "pathName=" + pathName_ ); } nextIndex_++; @@ -941,15 +954,15 @@ void SourceDestBufferImpl::setNextString( const ustring &value ) { /// don't checkImageFileOpen - if ( memoryRepresentation_ != E57_USTRING ) + if ( memoryRepresentation_ != UString ) { - throw E57_EXCEPTION2( E57_ERROR_EXPECTING_USTRING, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorExpectingUString, "pathName=" + pathName_ ); } /// Verify have room. if ( nextIndex_ >= capacity_ ) { - throw E57_EXCEPTION2( E57_ERROR_INTERNAL, "pathName=" + pathName_ ); + throw E57_EXCEPTION2( ErrorInternal, "pathName=" + pathName_ ); } /// Assign to already initialized element in vector @@ -957,38 +970,41 @@ void SourceDestBufferImpl::setNextString( const ustring &value ) nextIndex_++; } -void SourceDestBufferImpl::checkCompatible( const std::shared_ptr &newBuf ) const +void SourceDestBufferImpl::checkCompatible( + const std::shared_ptr &newBuf ) const { if ( pathName_ != newBuf->pathName() ) { - throw E57_EXCEPTION2( E57_ERROR_BUFFERS_NOT_COMPATIBLE, + throw E57_EXCEPTION2( ErrorBuffersNotCompatible, "pathName=" + pathName_ + " newPathName=" + newBuf->pathName() ); } if ( memoryRepresentation_ != newBuf->memoryRepresentation() ) { - throw E57_EXCEPTION2( E57_ERROR_BUFFERS_NOT_COMPATIBLE, + throw E57_EXCEPTION2( ErrorBuffersNotCompatible, "memoryRepresentation=" + toString( memoryRepresentation_ ) + " newMemoryType=" + toString( newBuf->memoryRepresentation() ) ); } if ( capacity_ != newBuf->capacity() ) { - throw E57_EXCEPTION2( E57_ERROR_BUFFERS_NOT_COMPATIBLE, - "capacity=" + toString( capacity_ ) + " newCapacity=" + toString( newBuf->capacity() ) ); + throw E57_EXCEPTION2( ErrorBuffersNotCompatible, + "capacity=" + toString( capacity_ ) + + " newCapacity=" + toString( newBuf->capacity() ) ); } if ( doConversion_ != newBuf->doConversion() ) { - throw E57_EXCEPTION2( E57_ERROR_BUFFERS_NOT_COMPATIBLE, + throw E57_EXCEPTION2( ErrorBuffersNotCompatible, "doConversion=" + toString( doConversion_ ) + "newDoConversion=" + toString( newBuf->doConversion() ) ); } if ( stride_ != newBuf->stride() ) { - throw E57_EXCEPTION2( E57_ERROR_BUFFERS_NOT_COMPATIBLE, - "stride=" + toString( stride_ ) + " newStride=" + toString( newBuf->stride() ) ); + throw E57_EXCEPTION2( ErrorBuffersNotCompatible, + "stride=" + toString( stride_ ) + + " newStride=" + toString( newBuf->stride() ) ); } } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void SourceDestBufferImpl::dump( int indent, std::ostream &os ) { /// don't checkImageFileOpen @@ -997,45 +1013,47 @@ void SourceDestBufferImpl::dump( int indent, std::ostream &os ) os << space( indent ) << "memoryRepresentation: "; switch ( memoryRepresentation_ ) { - case E57_INT8: + case Int8: os << "int8_t" << std::endl; break; - case E57_UINT8: + case UInt8: os << "uint8_t" << std::endl; break; - case E57_INT16: + case Int16: os << "int16_t" << std::endl; break; - case E57_UINT16: + case UInt16: os << "uint16_t" << std::endl; break; - case E57_INT32: + case Int32: os << "int32_t" << std::endl; break; - case E57_UINT32: + case UInt32: os << "uint32_t" << std::endl; break; - case E57_INT64: + case Int64: os << "int64_t" << std::endl; break; - case E57_BOOL: + case Bool: os << "bool" << std::endl; break; - case E57_REAL32: + case Real32: os << "float" << std::endl; break; - case E57_REAL64: + case Real64: os << "double" << std::endl; break; - case E57_USTRING: + case UString: os << "ustring" << std::endl; break; default: os << "" << std::endl; break; } - os << space( indent ) << "base: " << static_cast( base_ ) << std::endl; - os << space( indent ) << "ustrings: " << static_cast( ustrings_ ) << std::endl; + os << space( indent ) << "base: " << static_cast( base_ ) + << std::endl; + os << space( indent ) << "ustrings: " << static_cast( ustrings_ ) + << std::endl; os << space( indent ) << "capacity: " << capacity_ << std::endl; os << space( indent ) << "doConversion: " << doConversion_ << std::endl; os << space( indent ) << "doScaling: " << doScaling_ << std::endl; diff --git a/src/3rdParty/libE57Format/src/SourceDestBufferImpl.h b/src/3rdParty/libE57Format/src/SourceDestBufferImpl.h index 896b45dda2350..f981a9a23e661 100644 --- a/src/3rdParty/libE57Format/src/SourceDestBufferImpl.h +++ b/src/3rdParty/libE57Format/src/SourceDestBufferImpl.h @@ -36,12 +36,13 @@ namespace e57 class SourceDestBufferImpl : public std::enable_shared_from_this { public: - SourceDestBufferImpl( ImageFileImplWeakPtr destImageFile, const ustring &pathName, const size_t capacity, - bool doConversion = false, bool doScaling = false ); + SourceDestBufferImpl( ImageFileImplWeakPtr destImageFile, const ustring &pathName, + size_t capacity, bool doConversion = false, bool doScaling = false ); template void setTypeInfo( T *base, size_t stride = sizeof( T ) ); - SourceDestBufferImpl( ImageFileImplWeakPtr destImageFile, const ustring &pathName, StringList *b ); + SourceDestBufferImpl( ImageFileImplWeakPtr destImageFile, const ustring &pathName, + StringList *b ); ImageFileImplWeakPtr destImageFile() const { @@ -52,38 +53,47 @@ namespace e57 { return pathName_; } + MemoryRepresentation memoryRepresentation() const { return memoryRepresentation_; } + void *base() const { return base_; } + StringList *ustrings() const { return ustrings_; } + bool doConversion() const { return doConversion_; } + bool doScaling() const { return doScaling_; } + size_t stride() const { return stride_; } + size_t capacity() const { return capacity_; } + unsigned nextIndex() const { return nextIndex_; } + void rewind() { nextIndex_ = 0; @@ -102,31 +112,44 @@ namespace e57 void checkCompatible( const std::shared_ptr &newBuf ) const; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ); #endif private: template void _setNextReal( T inValue ); - void checkState_() const; /// Common routine to check that constructor - /// arguments were ok, throws if not + /// Common routine to check that constructor arguments were ok, throws if not + void checkState_() const; - //??? verify alignment ImageFileImplWeakPtr destImageFile_; - ustring pathName_; /// Pathname from CompressedVectorNode to source/dest - /// object, e.g. "Indices/0" - MemoryRepresentation memoryRepresentation_; /// Type of element (e.g. E57_INT8, E57_UINT64, - /// DOUBLE...) - char *base_ = nullptr; /// Address of first element, for non-ustring buffers - size_t capacity_ = 0; /// Total number of elements in array - bool doConversion_ = false; /// Convert memory representation to/from disk representation - bool doScaling_ = false; /// Apply scale factor for integer type - size_t stride_ = 0; /// Distance between each element (different than size_ - /// if elements not contiguous) - unsigned nextIndex_ = 0; /// Number of elements that have been set (dest - /// buffer) or read (source buffer) since rewind(). - StringList *ustrings_ = nullptr; /// Optional array of ustrings (used if - /// memoryRepresentation_==E57_USTRING) ???ownership + + /// Pathname from CompressedVectorNode to source/dest object, e.g. "Indices/0" + ustring pathName_; + + /// Type of element (e.g. ::Int8, ::UIin64, ::Real64...) + MemoryRepresentation memoryRepresentation_; + + /// Address of first element, for non-ustring buffers + char *base_ = nullptr; + + /// Total number of elements in array + size_t capacity_ = 0; + + /// Convert memory representation to/from disk representation + bool doConversion_ = false; + + /// Apply scale factor for integer type + bool doScaling_ = false; + + /// Distance between each element (different from size_ if elements not contiguous) + size_t stride_ = 0; + + /// Number of elements that have been set (dest buffer) or read (source buffer) since + /// rewind(). + unsigned nextIndex_ = 0; + + /// Optional array of ustrings (used if memoryRepresentation_ == ::UString) + StringList *ustrings_ = nullptr; }; } diff --git a/src/3rdParty/libE57Format/src/StringFunctions.cpp b/src/3rdParty/libE57Format/src/StringFunctions.cpp new file mode 100644 index 0000000000000..056a4aa32f8fe --- /dev/null +++ b/src/3rdParty/libE57Format/src/StringFunctions.cpp @@ -0,0 +1,73 @@ +#include "StringFunctions.h" + +#include +#include + +namespace e57 +{ + template std::string floatingPointToStr( FTYPE value, int precision ) + { + static_assert( std::is_floating_point::value, "Floating point type required." ); + + std::stringstream ss; + ss.imbue( std::locale::classic() ); + + ss << std::scientific << std::setprecision( precision ) << value; + + // Try to remove trailing zeroes and decimal point + // e.g. 1.23456000000000000e+005 ==> 1.23456e+005 + // e.g. 2.00000000000000000e+005 ==> 2e+005 + + std::string s = ss.str(); + + // Split into mantissa and exponent + // e.g. 1.23456000000000000e+005 ==> "1.23456000000000000" + "e+005" + auto index = s.find_last_of( 'e' ); + assert( index != std::string::npos ); // should not be possible + + std::string mantissa = s.substr( 0, index ); + const std::string exponent = s.substr( index ); + + // Double check that we understand the formatting + if ( exponent[0] == 'e' ) + { + // Trim trailing zeros from mantissa + while ( mantissa.back() == '0' ) + { + mantissa.pop_back(); + } + + // Trim trailing decimal point if possible + if ( mantissa.back() == '.' ) + { + mantissa.pop_back(); + } + + // Reassemble whole floating point number + // Check if can drop exponent. + if ( ( exponent == "e+00" ) || ( exponent == "e+000" ) ) + { + s = mantissa; + } + else + { + s = mantissa + exponent; + } + } + + return s; + } + + template std::string floatingPointToStr( float value, int precision ); + template std::string floatingPointToStr( double value, int precision ); + + double strToDouble( const std::string &inStr ) + { + std::istringstream iss{ inStr }; + iss.imbue( std::locale::classic() ); + double res = 0.; + iss >> res; + return res; + } + +} diff --git a/src/3rdParty/libE57Format/src/StringFunctions.h b/src/3rdParty/libE57Format/src/StringFunctions.h new file mode 100644 index 0000000000000..b40b1197a792e --- /dev/null +++ b/src/3rdParty/libE57Format/src/StringFunctions.h @@ -0,0 +1,206 @@ +/* + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2022 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace e57 +{ + /// @brief Create whitespace of given length, for indenting printouts in dump() functions + inline std::string space( size_t n ) + { + return std::string( n, ' ' ); + } + + /// @brief Convert number to decimal string + template std::string toString( T x ) + { + static_assert( std::is_integral::value || std::is_enum::value || + std::is_floating_point::value, + "Numeric type required." ); + + std::ostringstream ss; + ss << x; + return ss.str(); + } + + /// @overload + inline std::string hexString( uint8_t x ) + { + std::ostringstream ss; + ss << "0x" << std::hex << std::setw( 2 ) << std::setfill( '0' ) << static_cast( x ); + return ss.str(); + } + + /// @overload + inline std::string hexString( uint16_t x ) + { + std::ostringstream ss; + ss << "0x" << std::hex << std::setw( 4 ) << std::setfill( '0' ) << x; + return ss.str(); + } + + /// @overload + inline std::string hexString( uint32_t x ) + { + std::ostringstream ss; + ss << "0x" << std::hex << std::setw( 8 ) << std::setfill( '0' ) << x; + return ss.str(); + } + + /// @overload + inline std::string hexString( uint64_t x ) + { + std::ostringstream ss; + ss << "0x" << std::hex << std::setw( 16 ) << std::setfill( '0' ) << x; + return ss.str(); + } + + /// @overload + inline std::string hexString( int8_t x ) + { + return hexString( static_cast( x ) ); + } + + /// @brief Convert number to a hexadecimal strings + /// @note Hex strings don't have leading zeros. + inline std::string hexString( int16_t x ) + { + return hexString( static_cast( x ) ); + } + + /// @overload + inline std::string hexString( int32_t x ) + { + return hexString( static_cast( x ) ); + } + + /// @overload + inline std::string hexString( int64_t x ) + { + return hexString( static_cast( x ) ); + } + + /// @brief Convert number to a binary string + inline std::string binaryString( uint8_t x ) + { + std::ostringstream ss; + for ( int i = 7; i >= 0; i-- ) + { + ss << ( ( x & ( 1LL << i ) ) ? 1 : 0 ); + if ( i > 0 && i % 8 == 0 ) + { + ss << " "; + } + } + return ss.str(); + } + + /// @overload + inline std::string binaryString( uint16_t x ) + { + std::ostringstream ss; + for ( int i = 15; i >= 0; i-- ) + { + ss << ( ( x & ( 1LL << i ) ) ? 1 : 0 ); + if ( i > 0 && i % 8 == 0 ) + { + ss << " "; + } + } + return ss.str(); + } + + /// @overload + inline std::string binaryString( uint32_t x ) + { + std::ostringstream ss; + for ( int i = 31; i >= 0; i-- ) + { + ss << ( ( x & ( 1LL << i ) ) ? 1 : 0 ); + if ( i > 0 && i % 8 == 0 ) + { + ss << " "; + } + } + return ss.str(); + } + + /// @overload + inline std::string binaryString( uint64_t x ) + { + std::ostringstream ss; + for ( int i = 63; i >= 0; i-- ) + { + ss << ( ( x & ( 1LL << i ) ) ? 1 : 0 ); + if ( i > 0 && i % 8 == 0 ) + { + ss << " "; + } + } + return ss.str(); + } + + /// @overload + inline std::string binaryString( int8_t x ) + { + return binaryString( static_cast( x ) ); + } + + /// @overload + inline std::string binaryString( int16_t x ) + { + return binaryString( static_cast( x ) ); + } + + /// @overload + inline std::string binaryString( int32_t x ) + { + return binaryString( static_cast( x ) ); + } + + /// @overload + inline std::string binaryString( int64_t x ) + { + return binaryString( static_cast( x ) ); + } + + /// @brief Convert a floating point number to a string and do some clean up of the string. + template std::string floatingPointToStr( FTYPE value, int precision ); + + extern template std::string floatingPointToStr( float value, int precision ); + extern template std::string floatingPointToStr( double value, int precision ); + + /// Parse a double according the the classic ("C") locale. + /// @return The parsed double or 0.0 on error. + double strToDouble( const std::string &inStr ); +} diff --git a/src/3rdParty/libE57Format/src/StringNode.cpp b/src/3rdParty/libE57Format/src/StringNode.cpp new file mode 100644 index 0000000000000..b8c429a9096c6 --- /dev/null +++ b/src/3rdParty/libE57Format/src/StringNode.cpp @@ -0,0 +1,254 @@ +/* + * StringNode.cpp - implementation of public functions of the StringNode class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file StringNode.cpp + +#include "StringFunctions.h" +#include "StringNodeImpl.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/*! +@brief Check whether StringNode class invariant is true +@copydetails IntegerNode::checkInvariant() +*/ +void StringNode::checkInvariant( bool /*doRecurse*/, bool doUpcast ) const +{ + // If destImageFile not open, can't test invariant (almost every call would + // throw) + if ( !destImageFile().isOpen() ) + { + return; + } + + // If requested, call Node::checkInvariant + if ( doUpcast ) + { + static_cast( *this ).checkInvariant( false, false ); + } + // ? check legal UTF-8 +} + +/*! +@class e57::StringNode + +@brief An E57 element encoding a Unicode character string value. + +@details +A StringNode is a terminal node (i.e. having no children) that holds an Unicode character string +encoded in UTF-8. Once the StringNode value is set at creation, it may not be modified. + +See Node class discussion for discussion of the common functions that StructureNode supports. + +@section StringNode_invariant Class Invariant +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude StringNode.cpp +@skip void StringNode::checkInvariant +@until ^} + +@see Node +*/ + +/*! +@brief Create an element storing a Unicode character string. + +@param [in] destImageFile The ImageFile where the new node will eventually be stored. +@param [in] value The Unicode character string value of the element, in UTF-8 encoding. + +@details +The StringNode class corresponds to the ASTM E57 standard String element. See the class discussion +at bottom of StringNode page for more details. + +The @a destImageFile indicates which ImageFile the StringNode will eventually be attached to. A node +is attached to an ImageFile by adding it underneath the predefined root of the ImageFile (gotten +from ImageFile::root). It is not an error to fail to attach the StringNode to the @a destImageFile. +It is an error to attempt to attach the StringNode to a different ImageFile. + +If the StringNode is to be used in a CompressedVectorNode prototype, it is recommended to specify a +@a value = "" (the default value). + +@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be true). +@pre The @a destImageFile must have been opened in write mode (i.e. destImageFile.isWritable() must +be true). + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorFileReadOnly +@throw ::ErrorInternal All objects in undocumented state + +@see StringNode::value, Node, CompressedVectorNode, CompressedVectorNode::prototype +*/ +StringNode::StringNode( const ImageFile &destImageFile, const ustring &value ) : + impl_( new StringNodeImpl( destImageFile.impl(), value ) ) +{ +} + +/*! +@brief Is this a root node. +@copydetails Node::isRoot() +*/ +bool StringNode::isRoot() const +{ + return impl_->isRoot(); +} + +/*! +@brief Return parent of node, or self if a root node. +@copydetails Node::parent() +*/ +Node StringNode::parent() const +{ + return Node( impl_->parent() ); +} + +/*! +@brief Get absolute pathname of node. +@copydetails Node::pathName() +*/ +ustring StringNode::pathName() const +{ + return impl_->pathName(); +} + +/*! +@brief Get elementName string, that identifies the node in its parent. +@copydetails Node::elementName() +*/ +ustring StringNode::elementName() const +{ + return impl_->elementName(); +} + +/*! +@brief Get the ImageFile that was declared as the destination for the node when it was created. +@copydetails Node::destImageFile() +*/ +ImageFile StringNode::destImageFile() const +{ + return ImageFile( impl_->destImageFile() ); +} + +/*! +@brief Has node been attached into the tree of an ImageFile. +@copydetails Node::isAttached() +*/ +bool StringNode::isAttached() const +{ + return impl_->isAttached(); +} + +/*! +@brief Get Unicode character string value stored. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). + +@post No visible state is modified. + +@return The Unicode character string value stored. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state +*/ +ustring StringNode::value() const +{ + return impl_->value(); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void StringNode::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void StringNode::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif + +/*! +@brief Upcast a StringNode handle to a generic Node handle. + +@details +An upcast is always safe, and the compiler can automatically insert it for initializations of Node +variables and Node function arguments. + +@return A smart Node handle referencing the underlying object. + +@throw No E57Exceptions. + +@see Explanation in Node, Node::type(), StringNode(const Node&) +*/ +StringNode::operator Node() const +{ + /// Upcast from shared_ptr to SharedNodeImplPtr and construct + /// a Node object + return Node( impl_ ); +} + +/*! +@brief Downcast a generic Node handle to a StringNode handle. + +@param [in] n The generic handle to downcast. + +@details +The handle @a n must be for an underlying StringNode, otherwise an exception is thrown. In designs +that need to avoid the exception, use Node::type() to determine the actual type of the @a n before +downcasting. This function must be explicitly called (c++ compiler cannot insert it automatically). + +@throw ::ErrorBadNodeDowncast + +@see Node::type(), StringNode::operator Node() +*/ +StringNode::StringNode( const Node &n ) +{ + if ( n.type() != TypeString ) + { + throw E57_EXCEPTION2( ErrorBadNodeDowncast, "nodeType=" + toString( n.type() ) ); + } + + /// Set our shared_ptr to the downcast shared_ptr + impl_ = std::static_pointer_cast( n.impl() ); +} + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +StringNode::StringNode( std::shared_ptr ni ) : impl_( ni ) +{ +} +/// @endcond diff --git a/src/3rdParty/libE57Format/src/StringNodeImpl.cpp b/src/3rdParty/libE57Format/src/StringNodeImpl.cpp index 8d03d5813851f..4da8d3b53c84d 100644 --- a/src/3rdParty/libE57Format/src/StringNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/StringNodeImpl.cpp @@ -27,6 +27,7 @@ #include "StringNodeImpl.h" #include "CheckedFile.h" +#include "StringFunctions.h" namespace e57 { @@ -40,15 +41,15 @@ namespace e57 { // don't checkImageFileOpen - /// Same node type? - if ( ni->type() != E57_STRING ) + // Same node type? + if ( ni->type() != TypeString ) { return ( false ); } - /// ignore value_, doesn't have to match + // ignore value_, doesn't have to match - /// Types match + // Types match return ( true ); } @@ -56,7 +57,7 @@ namespace e57 { // don't checkImageFileOpen - /// We have no sub-structure, so if path not empty return false + // We have no sub-structure, so if path not empty return false return pathName.empty(); } @@ -70,10 +71,10 @@ namespace e57 { // don't checkImageFileOpen - /// We are a leaf node, so verify that we are listed in set. + // We are a leaf node, so verify that we are listed in set. if ( pathNames.find( relativePathName( origin ) ) == pathNames.end() ) { - throw E57_EXCEPTION2( E57_ERROR_NO_BUFFER_FOR_ELEMENT, "this->pathName=" + this->pathName() ); + throw E57_EXCEPTION2( ErrorNoBufferForElement, "this->pathName=" + this->pathName() ); } } @@ -83,7 +84,7 @@ namespace e57 // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName ) + if ( forcedFieldName != nullptr ) { fieldName = forcedFieldName; } @@ -94,7 +95,7 @@ namespace e57 cf << space( indent ) << "<" << fieldName << " type=\"String\""; - /// Write value as child text, unless it is the default value + // Write value as child text, unless it is the default value if ( value_.empty() ) { cf << "/>\n"; @@ -106,34 +107,34 @@ namespace e57 size_t currentPosition = 0; size_t len = value_.length(); - /// Loop, searching for occurrences of "]]>", which will be split across - /// two CDATA directives + // Loop, searching for occurrences of "]]>", which will be split across two CDATA + // directives while ( currentPosition < len ) { size_t found = value_.find( "]]>", currentPosition ); if ( found == std::string::npos ) { - /// Didn't find any more "]]>", so can send the rest. + // Didn't find any more "]]>", so can send the rest. cf << value_.substr( currentPosition ); break; } - /// Must output in two pieces, first send up to end of "]]" (don't send - /// the following ">"). + // Must output in two pieces, first send up to end of "]]" (don't send the following + // ">"). cf << value_.substr( currentPosition, found - currentPosition + 2 ); - /// Then start a new CDATA + // Then start a new CDATA cf << "]]>" plus the remaining part of the string + // Keep looping to send the ">" plus the remaining part of the string currentPosition = found + 2; } cf << "]]>\n"; } } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void StringNodeImpl::dump( int indent, std::ostream &os ) const { os << space( indent ) << "type: String" diff --git a/src/3rdParty/libE57Format/src/StringNodeImpl.h b/src/3rdParty/libE57Format/src/StringNodeImpl.h index 73dc4fa29434f..f6d1c51fe2ca6 100644 --- a/src/3rdParty/libE57Format/src/StringNodeImpl.h +++ b/src/3rdParty/libE57Format/src/StringNodeImpl.h @@ -38,8 +38,9 @@ namespace e57 NodeType type() const override { - return E57_STRING; + return TypeString; } + bool isTypeEquivalent( NodeImplSharedPtr ni ) override; bool isDefined( const ustring &pathName ) override; @@ -50,7 +51,7 @@ namespace e57 void writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, const char *forcedFieldName = nullptr ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif diff --git a/src/3rdParty/libE57Format/src/StructureNode.cpp b/src/3rdParty/libE57Format/src/StructureNode.cpp new file mode 100644 index 0000000000000..7eb4bec5b4fbc --- /dev/null +++ b/src/3rdParty/libE57Format/src/StructureNode.cpp @@ -0,0 +1,413 @@ +/* + * StructureNode.cpp - implementation of public functions of the StructureNode class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file StructureNode.cpp + +#include "StringFunctions.h" +#include "StructureNodeImpl.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/*! +@brief Check whether StructureNode class invariant is true +@copydetails IntegerNode::checkInvariant() +*/ +void StructureNode::checkInvariant( bool doRecurse, bool doUpcast ) const +{ + // If destImageFile not open, can't test invariant (almost every call would throw) + if ( !destImageFile().isOpen() ) + { + return; + } + + // If requested, call Node::checkInvariant + if ( doUpcast ) + { + static_cast( *this ).checkInvariant( false, false ); + } + + // Check each child + for ( int64_t i = 0; i < childCount(); i++ ) + { + Node child = get( i ); + + // If requested, check children recursively + if ( doRecurse ) + { + child.checkInvariant( doRecurse, true ); + } + + // Child's parent must be this + if ( static_cast( *this ) != child.parent() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Child's elementName must be defined + if ( !isDefined( child.elementName() ) ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Getting child by element name must yield same child + Node n = get( child.elementName() ); + if ( n != child ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } +} + +/*! +@class e57::StructureNode + +@brief An E57 element containing named child nodes. + +@details +A StructureNode is a container of named child nodes, which may be any of the eight node types. The +children of a structure node must have unique elementNames. Once a child node is set with a +particular elementName, it may not be modified. + +See Node class discussion for discussion of the common functions that StructureNode supports. + +@section structurenode_invariant Class Invariant +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude StructureNode.cpp +@skip void StructureNode::checkInvariant +@until ^} + +@see Node +*/ + +/*! +@brief Create an empty StructureNode. + +@param [in] destImageFile The ImageFile where the new node will eventually be stored. + +@details +A StructureNode is a container for collections of named E57 nodes. The @a destImageFile indicates +which ImageFile the StructureNode will eventually be attached to. A node is attached to an ImageFile +by adding it underneath the predefined root of the ImageFile (gotten from ImageFile::root). It is +not an error to fail to attach the StructureNode to the @a destImageFile. It is an error to attempt +to attach the StructureNode to a different ImageFile. + +@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be true). +@pre The @a destImageFile must have been opened in write mode (i.e. destImageFile.isWritable() must +be true). + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see Node +*/ +StructureNode::StructureNode( const ImageFile &destImageFile ) : + impl_( new StructureNodeImpl( destImageFile.impl() ) ) +{ +} + +/*! +@brief Is this a root node. +@copydetails Node::isRoot() +*/ +bool StructureNode::isRoot() const +{ + return impl_->isRoot(); +} + +/*! +@brief Return parent of node, or self if a root node. +@copydetails Node::parent() +*/ +Node StructureNode::parent() const +{ + return Node( impl_->parent() ); +} + +/*! +@brief Get absolute pathname of node. +@copydetails Node::pathName() +*/ +ustring StructureNode::pathName() const +{ + return impl_->pathName(); +} + +/*! +@brief Get elementName string, that identifies the node in its parent. +@copydetails Node::elementName() +*/ +ustring StructureNode::elementName() const +{ + return impl_->elementName(); +} + +/*! +@brief Get the ImageFile that was declared as the destination for the node when it was created. +@copydetails Node::destImageFile() +*/ +ImageFile StructureNode::destImageFile() const +{ + return ImageFile( impl_->destImageFile() ); +} + +/*! +@brief Has node been attached into the tree of an ImageFile. +@copydetails Node::isAttached() +*/ +bool StructureNode::isAttached() const +{ + return impl_->isAttached(); +} + +/*! +@brief Return number of child nodes contained by this StructureNode. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return Number of child nodes contained by this StructureNode. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see StructureNode::get(int64_t) const, +StructureNode::set, VectorNode::childCount +*/ +int64_t StructureNode::childCount() const +{ + return impl_->childCount(); +} + +/*! +@brief Is the given pathName defined relative to this node. + +@param [in] pathName The absolute pathname, or pathname relative to this object, to check. + +@details +The @a pathName may be relative to this node, or absolute (starting with a "/"). The origin of the +absolute path name is the root of the tree that contains this StructureNode. If this StructureNode +is not attached to an ImageFile, the @a pathName origin root will not the root node of an ImageFile. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return true if pathName is currently defined. + +@throw ::ErrorBadPathName +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ImageFile::root, VectorNode::isDefined +*/ +bool StructureNode::isDefined( const ustring &pathName ) const +{ + return impl_->isDefined( pathName ); +} + +/*! +@brief Get a child element by positional index. + +@param [in] index The index of child element to get, starting at 0. + +@details +The order of children is not specified, and may be different than order the children were added to +the StructureNode. The order of children may change if more children are added to the StructureNode. + +@pre 0 <= @a index < childCount() +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return A smart Node handle referencing the child node. + +@throw ::ErrorChildIndexOutOfBounds +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see StructureNode::childCount, +StructureNode::get(const ustring&) const, VectorNode::get +*/ +Node StructureNode::get( int64_t index ) const +{ + return Node( impl_->get( index ) ); +} + +/*! +@brief Get a child by path name. + +@param [in] pathName The absolute pathname, or pathname relative to this object, of the object to +get. The @a pathName may be relative to this node, or absolute (starting with a "/"). The origin of +the absolute path name is the root of the tree that contains this StructureNode. If this +StructureNode is not attached to an ImageFile, the @a pathName origin root will not the root node of +an ImageFile. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@pre The @a pathName must be defined (i.e. isDefined(pathName)). +@post No visible state is modified. + +@return A smart Node handle referencing the child node. + +@throw ::ErrorBadPathName +@throw ::ErrorPathUndefined +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see StructureNode::get(int64_t) const +*/ +Node StructureNode::get( const ustring &pathName ) const +{ + return Node( impl_->get( pathName ) ); +} + +/*! +@brief Add a new child at a given path + +@param [in] pathName The absolute pathname, or pathname relative to this object, that the child +object @a n will be given. +@param [in] n The node to be added to the tree with given @a pathName. + +@details +The @a pathName may be relative to this node, or absolute (starting with a "/"). The origin of the +absolute path name is the root of the tree that contains this StructureNode. If this StructureNode +is not attached to an ImageFile, the @a pathName origin root will not the root node of an ImageFile. + +The path name formed from all element names in @a pathName except the last must exist. If the @a +pathName identifies the child of a VectorNode, then the last element name in @a pathName must be +numeric, and be equal to the childCount of that VectorNode (the request is equivalent to +VectorNode::append). The StructureNode must not be a descendent of a homogeneous VectorNode with +more than one child. + +The element naming grammar specified by the ASTM E57 format standard are not enforced in this +function. This would be very difficult to do dynamically, as some of the naming rules involve +combinations of names. + +@pre The new child node @a n must be a root node (i.e. n.isRoot()). +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@pre The associated destImageFile must have been opened in write mode (i.e. +destImageFile().isWritable()). +@pre The @a pathName must not already be defined (i.e. !isDefined(pathName)). +@pre The associated destImageFile of this StructureNode and of @a n must be same (i.e. +destImageFile() == n.destImageFile()). +@post The @a pathName will be defined (i.e. isDefined(pathName)). + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorBadPathName +@throw ::ErrorPathUndefined +@throw ::ErrorSetTwice +@throw ::ErrorAlreadyHasParent +@throw ::ErrorDifferentDestImageFile +@throw ::ErrorHomogeneousViolation +@throw ::ErrorFileReadOnly +@throw ::ErrorInternal All objects in undocumented state + +@see VectorNode::append +*/ +void StructureNode::set( const ustring &pathName, const Node &n ) +{ + impl_->set( pathName, n.impl(), false ); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void StructureNode::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void StructureNode::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif + +/*! +@brief Upcast a StructureNode handle to a generic Node handle. + +@details +An upcast is always safe, and the compiler can automatically insert it for initializations of Node +variables and Node function arguments. + +@return A smart Node handle referencing the underlying object. + +@throw No E57Exceptions. + +@see explanation in Node, Node::type(), StructureNode(const Node&) +*/ +StructureNode::operator Node() const +{ + // Implicitly upcast from shared_ptr to SharedNodeImplPtr and construct a Node + // object + return Node( impl_ ); +} + +/*! +@brief Downcast a generic Node handle to a StructureNode handle. + +@param [in] n The generic handle to downcast. + +@details +The handle @a n must be for an underlying StructureNode, otherwise an exception is thrown. In +designs that need to avoid the exception, use Node::type() to determine the actual type of the @a n +before downcasting. This function must be explicitly called (c++ compiler cannot insert it +automatically). + +@throw ::ErrorBadNodeDowncast + +@see Node::type(), StructureNode::operator Node() +*/ +StructureNode::StructureNode( const Node &n ) +{ + if ( n.type() != TypeStructure ) + { + throw E57_EXCEPTION2( ErrorBadNodeDowncast, "nodeType=" + toString( n.type() ) ); + } + + // Set our shared_ptr to the downcast shared_ptr + impl_ = std::static_pointer_cast( n.impl() ); +} + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +StructureNode::StructureNode( std::weak_ptr fileParent ) : + impl_( new StructureNodeImpl( fileParent ) ) +{ +} + +StructureNode::StructureNode( std::shared_ptr ni ) : impl_( ni ) +{ +} +/// @endcond diff --git a/src/3rdParty/libE57Format/src/StructureNodeImpl.cpp b/src/3rdParty/libE57Format/src/StructureNodeImpl.cpp index e4aacb6ca0ded..aed51b922f02d 100644 --- a/src/3rdParty/libE57Format/src/StructureNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/StructureNodeImpl.cpp @@ -29,46 +29,48 @@ #include "CheckedFile.h" #include "ImageFileImpl.h" +#include "StringFunctions.h" #include "StructureNodeImpl.h" using namespace e57; -StructureNodeImpl::StructureNodeImpl( ImageFileImplWeakPtr destImageFile ) : NodeImpl( destImageFile ) +StructureNodeImpl::StructureNodeImpl( ImageFileImplWeakPtr destImageFile ) : + NodeImpl( destImageFile ) { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); } NodeType StructureNodeImpl::type() const { - /// don't checkImageFileOpen - return E57_STRUCTURE; + // don't checkImageFileOpen + return TypeStructure; } //??? use visitor? bool StructureNodeImpl::isTypeEquivalent( NodeImplSharedPtr ni ) { - /// don't checkImageFileOpen + // don't checkImageFileOpen - /// Same node type? - if ( ni->type() != E57_STRUCTURE ) + // Same node type? + if ( ni->type() != TypeStructure ) { return ( false ); } - /// Downcast to shared_ptr + // Downcast to shared_ptr std::shared_ptr si( std::static_pointer_cast( ni ) ); - /// Same number of children? + // Same number of children? if ( childCount() != si->childCount() ) { return ( false ); } - /// Check each child is equivalent + // Check each child is equivalent for ( unsigned i = 0; i < childCount(); i++ ) { //??? vector iterator? ustring myChildsFieldName = children_.at( i )->elementName(); - /// Check if matching field name is in same position (to speed things up) + // Check if matching field name is in same position (to speed things up) if ( myChildsFieldName == si->children_.at( i )->elementName() ) { if ( !children_.at( i )->isTypeEquivalent( si->children_.at( i ) ) ) @@ -78,8 +80,7 @@ bool StructureNodeImpl::isTypeEquivalent( NodeImplSharedPtr ni ) } else { - /// Children in different order, so lookup by name and check if equal - /// to our child + // Children in different order, so lookup by name and check if equal to our child if ( !si->isDefined( myChildsFieldName ) ) { return ( false ); @@ -91,7 +92,7 @@ bool StructureNodeImpl::isTypeEquivalent( NodeImplSharedPtr ni ) } } - /// Types match + // Types match return ( true ); } @@ -104,10 +105,10 @@ bool StructureNodeImpl::isDefined( const ustring &pathName ) void StructureNodeImpl::setAttachedRecursive() { - /// Mark this node as attached to an ImageFile + // Mark this node as attached to an ImageFile isAttached_ = true; - /// Not a leaf node, so mark all our children + // Not a leaf node, so mark all our children for ( auto &child : children_ ) { child->setAttachedRecursive(); @@ -120,14 +121,15 @@ int64_t StructureNodeImpl::childCount() const return children_.size(); } + NodeImplSharedPtr StructureNodeImpl::get( int64_t index ) { checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); if ( index < 0 || index >= static_cast( children_.size() ) ) { // %%% Possible truncation on platforms where size_t = uint64 - throw E57_EXCEPTION2( E57_ERROR_CHILD_INDEX_OUT_OF_BOUNDS, "this->pathName=" + this->pathName() + - " index=" + toString( index ) + - " size=" + toString( children_.size() ) ); + throw E57_EXCEPTION2( ErrorChildIndexOutOfBounds, + "this->pathName=" + this->pathName() + " index=" + toString( index ) + + " size=" + toString( children_.size() ) ); } return ( children_.at( static_cast( index ) ) ); } @@ -139,14 +141,15 @@ NodeImplSharedPtr StructureNodeImpl::get( const ustring &pathName ) if ( !ni ) { - throw E57_EXCEPTION2( E57_ERROR_PATH_UNDEFINED, "this->pathName=" + this->pathName() + " pathName=" + pathName ); + throw E57_EXCEPTION2( ErrorPathUndefined, + "this->pathName=" + this->pathName() + " pathName=" + pathName ); } return ( ni ); } NodeImplSharedPtr StructureNodeImpl::lookup( const ustring &pathName ) { - /// don't checkImageFileOpen + // don't checkImageFileOpen //??? use lookup(fields, level) instead, for speed. bool isRelative; std::vector fields; @@ -159,51 +162,46 @@ NodeImplSharedPtr StructureNodeImpl::lookup( const ustring &pathName ) { if ( isRelative ) { - return NodeImplSharedPtr(); /// empty pointer - } - else - { - NodeImplSharedPtr root( getRoot() ); - return ( root ); + return {}; // empty pointer } + + NodeImplSharedPtr root( getRoot() ); + return ( root ); } - else + + // Find child with elementName that matches first field in path + unsigned i; + for ( i = 0; i < children_.size(); i++ ) { - /// Find child with elementName that matches first field in path - unsigned i; - for ( i = 0; i < children_.size(); i++ ) + if ( fields.at( 0 ) == children_.at( i )->elementName() ) { - if ( fields.at( 0 ) == children_.at( i )->elementName() ) - { - break; - } - } - if ( i == children_.size() ) - { - return NodeImplSharedPtr(); /// empty pointer + break; } + } + if ( i == children_.size() ) + { + return {}; // empty pointer + } - if ( fields.size() == 1 ) - { - return ( children_.at( i ) ); - } + if ( fields.size() == 1 ) + { + return ( children_.at( i ) ); + } - //??? use level here rather than unparse - /// Remove first field in path - fields.erase( fields.begin() ); + //??? use level here rather than unparse + // Remove first field in path + fields.erase( fields.begin() ); - /// Call lookup on child object with remaining fields in path name - return children_.at( i )->lookup( imf->pathNameUnparse( true, fields ) ); - } + // Call lookup on child object with remaining fields in path name + return children_.at( i )->lookup( imf->pathNameUnparse( true, fields ) ); } - else - { /// Absolute pathname and we aren't at the root - /// Find root of the tree - NodeImplSharedPtr root( getRoot() ); - /// Call lookup on root - return ( root->lookup( pathName ) ); - } + // Absolute pathname and we aren't at the root + // Find root of the tree + NodeImplSharedPtr root( getRoot() ); + + // Call lookup on root + return ( root->lookup( pathName ) ); } void StructureNodeImpl::set( int64_t index64, NodeImplSharedPtr ni ) @@ -212,38 +210,39 @@ void StructureNodeImpl::set( int64_t index64, NodeImplSharedPtr ni ) auto index = static_cast( index64 ); - /// Allow index == current number of elements, interpret as append + // Allow index == current number of elements, interpret as append if ( index64 < 0 || index64 > UINT_MAX || index > children_.size() ) { - throw E57_EXCEPTION2( E57_ERROR_CHILD_INDEX_OUT_OF_BOUNDS, "this->pathName=" + this->pathName() + - " index=" + toString( index64 ) + - " size=" + toString( children_.size() ) ); + throw E57_EXCEPTION2( ErrorChildIndexOutOfBounds, + "this->pathName=" + this->pathName() + " index=" + toString( index64 ) + + " size=" + toString( children_.size() ) ); } - /// Enforce "set once" policy, only allow append + // Enforce "set once" policy, only allow append if ( index != children_.size() ) { - throw E57_EXCEPTION2( E57_ERROR_SET_TWICE, - "this->pathName=" + this->pathName() + " index=" + toString( index64 ) ); + throw E57_EXCEPTION2( ErrorSetTwice, "this->pathName=" + this->pathName() + + " index=" + toString( index64 ) ); } - /// Verify that child is destined for same ImageFile as this is + // Verify that child is destined for same ImageFile as this is ImageFileImplSharedPtr thisDest( destImageFile() ); ImageFileImplSharedPtr niDest( ni->destImageFile() ); if ( thisDest != niDest ) { - throw E57_EXCEPTION2( E57_ERROR_DIFFERENT_DEST_IMAGEFILE, - "this->destImageFile" + thisDest->fileName() + " ni->destImageFile" + niDest->fileName() ); + throw E57_EXCEPTION2( ErrorDifferentDestImageFile, + "this->destImageFile" + thisDest->fileName() + " ni->destImageFile" + + niDest->fileName() ); } - /// Field name is string version of index value, e.g. "14" + // Field name is string version of index value, e.g. "14" std::stringstream elementName; elementName << index; - /// If this struct is type constrained, can't add new child + // If this struct is type constrained, can't add new child if ( isTypeConstrained() ) { - throw E57_EXCEPTION2( E57_ERROR_HOMOGENEOUS_VIOLATION, "this->pathName=" + this->pathName() ); + throw E57_EXCEPTION2( ErrorHomogeneousViolation, "this->pathName=" + this->pathName() ); } ni->setParent( shared_from_this(), elementName.str() ); @@ -258,34 +257,33 @@ void StructureNodeImpl::set( const ustring &pathName, NodeImplSharedPtr ni, bool // types for VECTOR, // COMPRESSED_VECTOR -#ifdef E57_MAX_VERBOSE - std::cout << "StructureNodeImpl::set(pathName=" << pathName << ", ni, autoPathCreate=" << autoPathCreate - << std::endl; +#ifdef E57_VERBOSE + std::cout << "StructureNodeImpl::set(pathName=" << pathName + << ", ni, autoPathCreate=" << autoPathCreate << std::endl; #endif bool isRelative; std::vector fields; - /// Path may be absolute or relative with several levels. Break string into - /// individual levels. + // Path may be absolute or relative with several levels. Break string into individual levels. ImageFileImplSharedPtr imf( destImageFile_ ); imf->pathNameParse( pathName, isRelative, fields ); // throws if bad pathName if ( isRelative ) { - /// Relative path, starting from current object, e.g. "foo/17/bar" + // Relative path, starting from current object, e.g. "foo/17/bar" set( fields, 0, ni, autoPathCreate ); } else { - /// Absolute path (starting from root), e.g. "/foo/17/bar" + // Absolute path (starting from root), e.g. "/foo/17/bar" getRoot()->set( fields, 0, ni, autoPathCreate ); } } -void StructureNodeImpl::set( const std::vector &fields, unsigned level, NodeImplSharedPtr ni, - bool autoPathCreate ) +void StructureNodeImpl::set( const std::vector &fields, unsigned level, + NodeImplSharedPtr ni, bool autoPathCreate ) { -#ifdef E57_MAX_VERBOSE +#ifdef E57_VERBOSE std::cout << "StructureNodeImpl::set: level=" << level << std::endl; for ( unsigned i = 0; i < fields.size(); i++ ) { @@ -298,58 +296,56 @@ void StructureNodeImpl::set( const std::vector &fields, unsigned level, // index, else throw // bad_path - /// Check if trying to set the root node "/", which is illegal + // Check if trying to set the root node "/", which is illegal if ( level == 0 && fields.empty() ) { - throw E57_EXCEPTION2( E57_ERROR_SET_TWICE, "this->pathName=" + this->pathName() + " element=/" ); + throw E57_EXCEPTION2( ErrorSetTwice, "this->pathName=" + this->pathName() + " element=/" ); } - /// Serial search for matching field name, if find match, have error since - /// can't set twice + // Serial search for matching field name, if find match, have error since can't set twice for ( auto &child : children_ ) { if ( fields.at( level ) == child->elementName() ) { if ( level == fields.size() - 1 ) { - /// Enforce "set once" policy, don't allow reset - throw E57_EXCEPTION2( E57_ERROR_SET_TWICE, - "this->pathName=" + this->pathName() + " element=" + fields[level] ); + // Enforce "set once" policy, don't allow reset + throw E57_EXCEPTION2( ErrorSetTwice, "this->pathName=" + this->pathName() + + " element=" + fields[level] ); } - /// Recurse on child + // Recurse on child child->set( fields, level + 1, ni ); return; } } - /// Didn't find matching field name, so have a new child. + // Didn't find matching field name, so have a new child. - /// If this struct is type constrained, can't add new child + // If this struct is type constrained, can't add new child if ( isTypeConstrained() ) { - throw E57_EXCEPTION2( E57_ERROR_HOMOGENEOUS_VIOLATION, "this->pathName=" + this->pathName() ); + throw E57_EXCEPTION2( ErrorHomogeneousViolation, "this->pathName=" + this->pathName() ); } - /// Check if we are at bottom level + // Check if we are at bottom level if ( level == fields.size() - 1 ) { - /// At bottom, so append node at end of children + // At bottom, so append node at end of children ni->setParent( shared_from_this(), fields.at( level ) ); children_.push_back( ni ); } else { - /// Not at bottom level, if not autoPathCreate have an error + // Not at bottom level, if not autoPathCreate have an error if ( !autoPathCreate ) { - throw E57_EXCEPTION2( E57_ERROR_PATH_UNDEFINED, - "this->pathName=" + this->pathName() + " field=" + fields.at( level ) ); + throw E57_EXCEPTION2( ErrorPathUndefined, "this->pathName=" + this->pathName() + + " field=" + fields.at( level ) ); } //??? what if extra fields are numbers? - /// Do autoPathCreate: Create nested Struct objects for extra field names - /// in path + // Do autoPathCreate: Create nested Struct objects for extra field names in path NodeImplSharedPtr parent( shared_from_this() ); for ( ; level != fields.size() - 1; level++ ) { @@ -363,18 +359,18 @@ void StructureNodeImpl::set( const std::vector &fields, unsigned level, void StructureNodeImpl::append( NodeImplSharedPtr ni ) { - /// don't checkImageFileOpen, set() will do it + // don't checkImageFileOpen, set() will do it - /// Create new node at end of list with integer field name + // Create new node at end of list with integer field name set( childCount(), ni ); } //??? use visitor? void StructureNodeImpl::checkLeavesInSet( const StringSet &pathNames, NodeImplSharedPtr origin ) { - /// don't checkImageFileOpen + // don't checkImageFileOpen - /// Not a leaf node, so check all our children + // Not a leaf node, so check all our children for ( auto &child : children_ ) { child->checkLeavesInSet( pathNames, origin ); @@ -382,12 +378,13 @@ void StructureNodeImpl::checkLeavesInSet( const StringSet &pathNames, NodeImplSh } //??? use visitor? -void StructureNodeImpl::writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, const char *forcedFieldName ) +void StructureNodeImpl::writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, + const char *forcedFieldName ) { - /// don't checkImageFileOpen + // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName ) + if ( forcedFieldName != nullptr ) { fieldName = forcedFieldName; } @@ -400,9 +397,9 @@ void StructureNodeImpl::writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, i const int numSpaces = indent + static_cast( fieldName.length() ) + 2; - /// If this struct is the root for the E57 file, add name space declarations - /// Note the prototype of a CompressedVector is a separate tree, so don't - /// want to write out namespaces if not the ImageFile root + // If this struct is the root for the E57 file, add name space declarations. Note the prototype + // of a CompressedVector is a separate tree, so don't want to write out namespaces if not the + // ImageFile root if ( isRoot() && shared_from_this() == imf->root() ) { bool gotDefaultNamespace = false; @@ -426,38 +423,37 @@ void StructureNodeImpl::writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, i << imf->extensionsUri( index ) << "\""; } - /// If user didn't explicitly declare a default namespace, use the current - /// E57 standard one. + // If user didn't explicitly declare a default namespace, use the current E57 standard one. if ( !gotDefaultNamespace ) { - cf << "\n" << space( numSpaces ) << "xmlns=\"" << E57_V1_0_URI << "\""; + cf << "\n" << space( numSpaces ) << "xmlns=\"" << VERSION_1_0_URI << "\""; } } if ( !children_.empty() ) { cf << ">\n"; - /// Write all children nested inside Structure element + // Write all children nested inside Structure element for ( auto &child : children_ ) { child->writeXml( imf, cf, indent + 2 ); } - /// Write closing tag + // Write closing tag cf << space( indent ) << "\n"; } else { - /// XML element has no child elements + // XML element has no child elements cf << "/>\n"; } } //??? use visitor? -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void StructureNodeImpl::dump( int indent, std::ostream &os ) const { - /// don't checkImageFileOpen + // don't checkImageFileOpen os << space( indent ) << "type: Structure" << " (" << type() << ")" << std::endl; NodeImpl::dump( indent, os ); diff --git a/src/3rdParty/libE57Format/src/StructureNodeImpl.h b/src/3rdParty/libE57Format/src/StructureNodeImpl.h index 53546d92d3df9..3dbb09a0953eb 100644 --- a/src/3rdParty/libE57Format/src/StructureNodeImpl.h +++ b/src/3rdParty/libE57Format/src/StructureNodeImpl.h @@ -35,7 +35,7 @@ namespace e57 class StructureNodeImpl : public NodeImpl { public: - StructureNodeImpl( ImageFileImplWeakPtr destImageFile ); + explicit StructureNodeImpl( ImageFileImplWeakPtr destImageFile ); ~StructureNodeImpl() override = default; NodeType type() const override; @@ -49,8 +49,10 @@ namespace e57 NodeImplSharedPtr get( const ustring &pathName ) override; virtual void set( int64_t index, NodeImplSharedPtr ni ); - void set( const ustring &pathName, NodeImplSharedPtr ni, bool autoPathCreate = false ) override; - void set( const StringList &fields, unsigned level, NodeImplSharedPtr ni, bool autoPathCreate = false ) override; + void set( const ustring &pathName, NodeImplSharedPtr ni, + bool autoPathCreate = false ) override; + void set( const StringList &fields, unsigned level, NodeImplSharedPtr ni, + bool autoPathCreate = false ) override; virtual void append( NodeImplSharedPtr ni ); void checkLeavesInSet( const StringSet &pathNames, NodeImplSharedPtr origin ) override; @@ -58,12 +60,13 @@ namespace e57 void writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, const char *forcedFieldName = nullptr ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif protected: friend class CompressedVectorReaderImpl; + NodeImplSharedPtr lookup( const ustring &pathName ) override; std::vector children_; diff --git a/src/3rdParty/libE57Format/src/VectorNode.cpp b/src/3rdParty/libE57Format/src/VectorNode.cpp new file mode 100644 index 0000000000000..c684a4edf7d7d --- /dev/null +++ b/src/3rdParty/libE57Format/src/VectorNode.cpp @@ -0,0 +1,435 @@ +/* + * VectorNode.cpp - implementation of public functions of the VectorNode class. + * + * Original work Copyright 2009 - 2010 Kevin Ackley (kackley@gwi.net) + * Modified work Copyright 2018 - 2020 Andy Maloney + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/// @file VectorNode.cpp + +#include "StringFunctions.h" +#include "VectorNodeImpl.h" + +using namespace e57; + +// Put this function first so we can reference the code in doxygen using @skip +/*! +@brief Check whether VectorNode class invariant is true +@copydetails IntegerNode::checkInvariant() +*/ +void VectorNode::checkInvariant( bool doRecurse, bool doUpcast ) const +{ + // If destImageFile not open, can't test invariant (almost every call would throw) + if ( !destImageFile().isOpen() ) + { + return; + } + + // If requested, call Node::checkInvariant + if ( doUpcast ) + { + static_cast( *this ).checkInvariant( false, false ); + } + + // Check each child + for ( int64_t i = 0; i < childCount(); i++ ) + { + Node child = get( i ); + + // If requested, check children recursively + if ( doRecurse ) + { + child.checkInvariant( doRecurse, true ); + } + + // Child's parent must be this + if ( static_cast( *this ) != child.parent() ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Child's elementName must be defined + if ( !isDefined( child.elementName() ) ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + + // Getting child by element name must yield same child + Node n = get( child.elementName() ); + if ( n != child ) + { + throw E57_EXCEPTION1( ErrorInvarianceViolation ); + } + } +} + +/*! +@class e57::VectorNode + +@brief An E57 element containing ordered vector of child nodes. + +@details +A VectorNode is a container of ordered child nodes. The child nodes are automatically assigned an +elementName, which is a string version of the positional index of the child starting at "0". Child +nodes may only be appended onto the end of a VectorNode. + +A VectorNode that is created with a restriction that its children must have the same type is called +a "homogeneous VectorNode". A VectorNode without such a restriction is called a "heterogeneous +VectorNode". + +See Node class discussion for discussion of the common functions that StructureNode supports. + +@section vectornode_invariant Class Invariant +A class invariant is a list of statements about an object that are always true before and after any +operation on the object. An invariant is useful for testing correct operation of an implementation. +Statements in an invariant can involve only externally visible state, or can refer to internal +implementation-specific state that is not visible to the API user. The following C++ code checks +externally visible state for consistency and throws an exception if the invariant is violated: + +@dontinclude VectorNode.cpp +@skip void VectorNode::checkInvariant +@until ^} + +@see Node +*/ + +/*! +@brief Create a new empty Vector node. + +@param [in] destImageFile The ImageFile where the new node will eventually be stored. +@param [in] allowHeteroChildren Will child elements of differing types be allowed in this +VectorNode. + +@details +A VectorNode is a ordered container of E57 nodes. + +The @a destImageFile indicates which ImageFile the VectorNode will eventually be attached to. A node +is attached to an ImageFile by adding it underneath the predefined root of the ImageFile (gotten +from ImageFile::root). It is not an error to fail to attach the VectorNode to the @a destImageFile. +It is an error to attempt to attach the VectorNode to a different ImageFile. + +If @a allowHeteroChildren is false, then the children that are appended to the VectorNode must be +identical in every visible characteristic except the stored values. These visible characteristics +include number of children (for StructureNode and VectorNode descendents), number of +records/prototypes/codecs (for CompressedVectorNode), minimum/maximum attributes (for IntegerNode, +ScaledIntegerNode, FloatNode), byteCount (for BlobNode), scale/offset (for ScaledIntegerNode), and +all elementNames. The enforcement of this homogeneity rule begins when the second child is appended +to the VectorNode, thus it is not an error to modify a child of a homogeneous VectorNode containing +only one child. + +If @a allowHeteroChildren is true, then the types of the children of the VectorNode are completely +unconstrained. + +@pre The @a destImageFile must be open (i.e. destImageFile.isOpen() must be true). +@pre The @a destImageFile must have been opened in write mode (i.e. destImageFile.isWritable() must +be true). + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see Node, VectorNode::allowHeteroChildren, ::ErrorHomogeneousViolation +*/ +VectorNode::VectorNode( const ImageFile &destImageFile, bool allowHeteroChildren ) : + impl_( new VectorNodeImpl( destImageFile.impl(), allowHeteroChildren ) ) +{ +} + +/*! +@brief Is this a root node. +@copydetails Node::isRoot() +*/ +bool VectorNode::isRoot() const +{ + return impl_->isRoot(); +} + +/*! +@brief Return parent of node, or self if a root node. +@copydetails Node::parent() +*/ +Node VectorNode::parent() const +{ + return Node( impl_->parent() ); +} + +/*! +@brief Get absolute pathname of node. +@copydetails Node::pathName() +*/ +ustring VectorNode::pathName() const +{ + return impl_->pathName(); +} + +/*! +@brief Get elementName string, that identifies the node in its parent. +@copydetails Node::elementName() +*/ +ustring VectorNode::elementName() const +{ + return impl_->elementName(); +} + +/*! +@brief Get the ImageFile that was declared as the destination for the node when it was created. +@copydetails Node::destImageFile() +*/ +ImageFile VectorNode::destImageFile() const +{ + return ImageFile( impl_->destImageFile() ); +} + +/*! +@brief Has node been attached into the tree of an ImageFile. +@copydetails Node::isAttached() +*/ +bool VectorNode::isAttached() const +{ + return impl_->isAttached(); +} + +/*! +@brief Get whether child elements are allowed to be different types + +@details +See the class discussion at bottom of VectorNode page for details of homogeneous/heterogeneous +VectorNode. The returned attribute is determined when the VectorNode is created, and cannot be +changed. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return True if child elements can be different types. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see ::ErrorHomogeneousViolation +*/ +bool VectorNode::allowHeteroChildren() const +{ + return impl_->allowHeteroChildren(); +} + +/*! +@brief Get number of child elements in this VectorNode. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return Number of child elements in this VectorNode. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see VectorNode::get(int64_t), VectorNode::append, StructureNode::childCount +*/ +int64_t VectorNode::childCount() const +{ + return impl_->childCount(); +} + +/*! +@brief Is the given pathName defined relative to this node. + +@param [in] pathName The absolute pathname, or pathname relative to this object, to check. + +@details +The @a pathName may be relative to this node, or absolute (starting with a "/"). The origin of the +absolute path name is the root of the tree that contains this VectorNode. If this VectorNode is not +attached to an ImageFile, the @a pathName origin root will not the root node of an ImageFile. + +The element names of child elements of VectorNodes are numbers, encoded as strings, starting at "0". + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@post No visible state is modified. + +@return true if pathName is currently defined. + +@throw ::ErrorBadPathName +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see StructureNode::isDefined +*/ +bool VectorNode::isDefined( const ustring &pathName ) const +{ + return impl_->isDefined( pathName ); +} + +/*! +@brief Get a child element by positional index. + +@param [in] index The index of child element to get, starting at 0. + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@pre 0 <= @a index < childCount() +@post No visible state is modified. + +@return A smart Node handle referencing the child node. + +@throw ::ErrorChildIndexOutOfBounds +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see VectorNode::childCount, VectorNode::append, StructureNode::get(int64_t) const +*/ +Node VectorNode::get( int64_t index ) const +{ + return Node( impl_->get( index ) ); +} + +/*! +@brief Get a child element by string path name + +@param [in] pathName The pathname, either absolute or relative, of the object to get. + +@details +The @a pathName may be relative to this node, or absolute (starting with a "/"). The origin of the +absolute path name is the root of the tree that contains this VectorNode. If this VectorNode is not +attached to an ImageFile, the @a pathName origin root will not the root node of an ImageFile. + +The element names of child elements of VectorNodes are numbers, encoded as strings, starting at "0". + +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@pre The @a pathName must be defined (i.e. isDefined(pathName)). +@post No visible state is modified. + +@return A smart Node handle referencing the child node. + +@throw ::ErrorBadPathName +@throw ::ErrorPathUndefined +@throw ::ErrorImageFileNotOpen +@throw ::ErrorInternal All objects in undocumented state + +@see VectorNode::childCount, VectorNode::append, StructureNode::get(int64_t) const +*/ +Node VectorNode::get( const ustring &pathName ) const +{ + return Node( impl_->get( pathName ) ); +} + +/*! +@brief Append a child element to end of VectorNode. + +@param [in] n The node to be added as a child at end of the VectorNode. + +@details +If the VectorNode is homogeneous and already has at least one child, then @a n must be identical to +the existing children in every visible characteristic except the stored values. These visible +characteristics include number of children (for StructureNode and VectorNode descendents), number of +records/prototypes/codecs (for CompressedVectorNode), minimum/maximum attributes (for IntegerNode, +ScaledIntegerNode, FloatNode), byteCount (for BlobNode), scale/offset (for ScaledIntegerNode), and +all elementNames. + +The VectorNode must not be a descendent of a homogeneous VectorNode with more than one child. + +@pre The new child node @a n must be a root node (not already having a parent). +@pre The destination ImageFile must be open (i.e. destImageFile().isOpen()). +@pre The associated destImageFile must have been opened in write mode (i.e. +destImageFile().isWritable()). +@post the childCount is incremented. + +@throw ::ErrorImageFileNotOpen +@throw ::ErrorHomogeneousViolation +@throw ::ErrorFileReadOnly +@throw ::ErrorAlreadyHasParent +@throw ::ErrorDifferentDestImageFile +@throw ::ErrorInternal All objects in undocumented state + +@see VectorNode::childCount, VectorNode::get(int64_t), StructureNode::set +*/ +void VectorNode::append( const Node &n ) +{ + impl_->append( n.impl() ); +} + +/*! +@brief Diagnostic function to print internal state of object to output stream in an indented format. +@copydetails Node::dump() +*/ +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT +void VectorNode::dump( int indent, std::ostream &os ) const +{ + impl_->dump( indent, os ); +} +#else +void VectorNode::dump( int indent, std::ostream &os ) const +{ + UNUSED( indent ); + UNUSED( os ); +} +#endif + +/*! +@brief Upcast a VectorNode handle to a generic Node handle. + +@details +An upcast is always safe, and the compiler can automatically insert it for initializations of Node +variables and Node function arguments. + +@return A smart Node handle referencing the underlying object. + +@throw No E57Exceptions. + +@see explanation in Node, Node::type(), VectorNode(const Node&) +*/ +VectorNode::operator Node() const +{ + // Implicitly upcast from shared_ptr to SharedNodeImplPtr and construct a Node + // object + return Node( impl_ ); +} + +/*! +@brief Downcast a generic Node handle to a VectorNode handle. + +@param [in] n The generic handle to downcast. + +@details +The handle @a n must be for an underlying VectorNode, otherwise an exception is thrown. In designs +that need to avoid the exception, use Node::type() to determine the actual type of the @a n before +downcasting. This function must be explicitly called (c++ compiler cannot insert it automatically). + +@throw ::ErrorBadNodeDowncast + +@see Node::type(), VectorNode::operator Node() +*/ +VectorNode::VectorNode( const Node &n ) +{ + if ( n.type() != TypeVector ) + { + throw E57_EXCEPTION2( ErrorBadNodeDowncast, "nodeType=" + toString( n.type() ) ); + } + + // Set our shared_ptr to the downcast shared_ptr + impl_ = std::static_pointer_cast( n.impl() ); +} + +/// @cond documentNonPublic The following isn't part of the API, and isn't documented. +VectorNode::VectorNode( std::shared_ptr ni ) : impl_( ni ) +{ +} +/// @endcond diff --git a/src/3rdParty/libE57Format/src/VectorNodeImpl.cpp b/src/3rdParty/libE57Format/src/VectorNodeImpl.cpp index 9534375a2358d..d4863e3e4f413 100644 --- a/src/3rdParty/libE57Format/src/VectorNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/VectorNodeImpl.cpp @@ -27,40 +27,41 @@ #include "VectorNodeImpl.h" #include "CheckedFile.h" +#include "StringFunctions.h" namespace e57 { VectorNodeImpl::VectorNodeImpl( ImageFileImplWeakPtr destImageFile, bool allowHeteroChildren ) : StructureNodeImpl( destImageFile ), allowHeteroChildren_( allowHeteroChildren ) { - /// don't checkImageFileOpen, StructNodeImpl() will do it + // don't checkImageFileOpen, StructNodeImpl() will do it } bool VectorNodeImpl::isTypeEquivalent( NodeImplSharedPtr ni ) { - /// don't checkImageFileOpen + // don't checkImageFileOpen - /// Same node type? - if ( ni->type() != E57_VECTOR ) + // Same node type? + if ( ni->type() != TypeVector ) { return ( false ); } std::shared_ptr ai( std::static_pointer_cast( ni ) ); - /// allowHeteroChildren must match + // allowHeteroChildren must match if ( allowHeteroChildren_ != ai->allowHeteroChildren_ ) { return ( false ); } - /// Same number of children? + // Same number of children? if ( childCount() != ai->childCount() ) { return ( false ); } - /// Check each child, must be in same order + // Check each child, must be in same order for ( unsigned i = 0; i < childCount(); i++ ) { if ( !children_.at( i )->isTypeEquivalent( ai->children_.at( i ) ) ) @@ -69,7 +70,7 @@ namespace e57 } } - /// Types match + // Types match return ( true ); } @@ -84,26 +85,28 @@ namespace e57 checkImageFileOpen( __FILE__, __LINE__, static_cast( __FUNCTION__ ) ); if ( !allowHeteroChildren_ ) { - /// New node type must match all existing children + // New node type must match all existing children for ( auto &child : children_ ) { if ( !child->isTypeEquivalent( ni ) ) { - throw E57_EXCEPTION2( E57_ERROR_HOMOGENEOUS_VIOLATION, "this->pathName=" + this->pathName() ); + throw E57_EXCEPTION2( ErrorHomogeneousViolation, + "this->pathName=" + this->pathName() ); } } } - ///??? for now, use base implementation + //??? for now, use base implementation StructureNodeImpl::set( index64, ni ); } - void VectorNodeImpl::writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, const char *forcedFieldName ) + void VectorNodeImpl::writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, + const char *forcedFieldName ) { - /// don't checkImageFileOpen + // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName ) + if ( forcedFieldName != nullptr ) { fieldName = forcedFieldName; } @@ -121,13 +124,13 @@ namespace e57 cf << space( indent ) << "\n"; } -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void VectorNodeImpl::dump( int indent, std::ostream &os ) const { - /// don't checkImageFileOpen + // don't checkImageFileOpen os << space( indent ) << "type: Vector" << " (" << type() << ")" << std::endl; - NodeImpl::dump( indent, os ); + NodeImpl::dump( indent, os ); // NOLINT(bugprone-parent-virtual-call) os << space( indent ) << "allowHeteroChildren: " << allowHeteroChildren() << std::endl; for ( unsigned i = 0; i < children_.size(); i++ ) { diff --git a/src/3rdParty/libE57Format/src/VectorNodeImpl.h b/src/3rdParty/libE57Format/src/VectorNodeImpl.h index fc4adc825dce9..23e81ea0fd91b 100644 --- a/src/3rdParty/libE57Format/src/VectorNodeImpl.h +++ b/src/3rdParty/libE57Format/src/VectorNodeImpl.h @@ -38,7 +38,7 @@ namespace e57 NodeType type() const override { - return E57_VECTOR; + return TypeVector; } bool isTypeEquivalent( NodeImplSharedPtr ni ) override; @@ -49,11 +49,16 @@ namespace e57 void writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, int indent, const char *forcedFieldName = nullptr ) override; -#ifdef E57_DEBUG +#ifdef E57_ENABLE_DIAGNOSTIC_OUTPUT void dump( int indent = 0, std::ostream &os = std::cout ) const override; #endif private: + // Because we are overriding set(), it is hiding the other overrides in StructureNodeImpl. + // This will pull them in. + // Fixes the "overloaded-virtual" warning in gcc. + using StructureNodeImpl::set; + bool allowHeteroChildren_; }; } diff --git a/src/3rdParty/libE57Format/src/WriterImpl.cpp b/src/3rdParty/libE57Format/src/WriterImpl.cpp index f8942038b3310..34d2476cdfee3 100644 --- a/src/3rdParty/libE57Format/src/WriterImpl.cpp +++ b/src/3rdParty/libE57Format/src/WriterImpl.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) 2010 Stan Coleby (scoleby@intelisum.com) * Copyright (c) 2020 PTC Inc. + * Copyright (c) 2022 Andy Maloney * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by @@ -25,42 +26,136 @@ * DEALINGS IN THE SOFTWARE. */ +#include + #include "WriterImpl.h" #include "Common.h" -#include +#include "E57Version.h" + +namespace +{ + /*! + @brief Convert e57::NumericalNodeType into human-readable string. + + @param inNodeType node type to convert + + @return human-readable representation of node type or "Unknown: ". + */ + std::string _numericalNodeTypeStr( e57::NumericalNodeType inNodeType ) + { + switch ( inNodeType ) + { + case e57::NumericalNodeType::Integer: + { + return "Integer"; + } + + case e57::NumericalNodeType::ScaledInteger: + { + return "ScaledInteger"; + } + + case e57::NumericalNodeType::Float: + { + return "Float"; + } + + case e57::NumericalNodeType::Double: + { + return "Double"; + } + + default: + return std::string( "Unknown: " ) + .append( std::to_string( static_cast( inNodeType ) ) ); + } + } +} namespace e57 { + /*! + @brief This function writes the projection image + + @param image 1 of 3 projects or the visual + @param imageType identifies the image format desired. + @param pBuffer pointer the buffer + @param start position in the block to start reading + @param count size of desired chunk or buffer size + */ + static size_t _writeImage2DNode( const StructureNode &image, Image2DType imageType, + uint8_t *pBuffer, int64_t start, size_t count ) + { + size_t transferred = 0; + + switch ( imageType ) + { + case ImageNone: + return 0; - WriterImpl::WriterImpl( const ustring &filePath, const ustring &coordinateMetadata ) : + case ImageJPEG: + if ( image.isDefined( "jpegImage" ) ) + { + BlobNode jpegImage( image.get( "jpegImage" ) ); + jpegImage.write( pBuffer, start, count ); + transferred = count; + } + break; + + case ImagePNG: + if ( image.isDefined( "pngImage" ) ) + { + BlobNode pngImage( image.get( "pngImage" ) ); + pngImage.write( pBuffer, start, count ); + transferred = count; + } + break; + + case ImageMaskPNG: + if ( image.isDefined( "imageMask" ) ) + { + BlobNode imageMask( image.get( "imageMask" ) ); + imageMask.write( pBuffer, start, count ); + transferred = count; + } + break; + } + + return transferred; + } + + WriterImpl::WriterImpl( const ustring &filePath, const WriterOptions &options ) : imf_( filePath, "w" ), root_( imf_.root() ), data3D_( imf_, true ), images2D_( imf_, true ) { // We are using the E57 v1.0 data format standard fieldnames. // The standard fieldnames are used without an extension prefix (in the default namespace). - // We explicitly register it for completeness (the reference implementation would do it for us, if we didn't). - imf_.extensionsAdd( "", E57_V1_0_URI ); + // We explicitly register it for completeness (the reference implementation would do it for + // us, if we didn't). + imf_.extensionsAdd( "", e57::VERSION_1_0_URI ); // Set per-file properties. // Path names: "/formatName", "/majorVersion", "/minorVersion", "/coordinateMetadata" root_.set( "formatName", StringNode( imf_, "ASTM E57 3D Imaging Data File" ) ); - root_.set( "guid", StringNode( imf_, generateRandomGUID() ) ); - // Get ASTM version number supported by library, so can write it into file - int astmMajor; - int astmMinor; - ustring libraryId; - Utilities::getVersions( astmMajor, astmMinor, libraryId ); + if ( !options.guid.empty() ) + { + root_.set( "guid", StringNode( imf_, options.guid ) ); + } + else + { + root_.set( "guid", StringNode( imf_, generateRandomGUID() ) ); + } - root_.set( "versionMajor", IntegerNode( imf_, astmMajor ) ); - root_.set( "versionMinor", IntegerNode( imf_, astmMinor ) ); - root_.set( "e57LibraryVersion", StringNode( imf_, libraryId ) ); + root_.set( "versionMajor", IntegerNode( imf_, Version::astmMajor() ) ); + root_.set( "versionMinor", IntegerNode( imf_, Version::astmMinor() ) ); + root_.set( "e57LibraryVersion", StringNode( imf_, Version::library() ) ); // Save a dummy string for coordinate system. // Really should be a valid WKT string identifying the coordinate reference system (CRS). - if ( !coordinateMetadata.empty() ) + if ( !options.coordinateMetadata.empty() ) { - root_.set( "coordinateMetadata", StringNode( imf_, coordinateMetadata ) ); + root_.set( "coordinateMetadata", StringNode( imf_, options.coordinateMetadata ) ); } // Create creationDateTime structure @@ -68,10 +163,10 @@ namespace e57 // TODO currently no support for handling UTC <-> GPS time conversions // note that "creationDateTime" is optional in the standard #if 0 - StructureNode creationDateTime = StructureNode(imf_); - creationDateTime.set("dateTimeValue", FloatNode(imf_, GetGPSTime())); - creationDateTime.set("isAtomicClockReferenced", IntegerNode(imf_,0)); - root_.set("creationDateTime", creationDateTime); + StructureNode creationDateTime = StructureNode(imf_); + creationDateTime.set("dateTimeValue", FloatNode(imf_, GetGPSTime())); + creationDateTime.set("isAtomicClockReferenced", IntegerNode(imf_,0)); + root_.set("creationDateTime", creationDateTime); #endif root_.set( "data3D", data3D_ ); @@ -102,33 +197,13 @@ namespace e57 return true; } - StructureNode WriterImpl::GetRawE57Root() - { - return root_; - } - - VectorNode WriterImpl::GetRawData3D() - { - return data3D_; - } - - VectorNode WriterImpl::GetRawImages2D() - { - return images2D_; - } - - ImageFile WriterImpl::GetRawIMF() - { - return imf_; - } - int64_t WriterImpl::NewImage2D( Image2D &image2DHeader ) { - int64_t pos = -1; + StructureNode image( imf_ ); - StructureNode image = StructureNode( imf_ ); images2D_.append( image ); - pos = images2D_.childCount() - 1; + + int64_t pos = images2D_.childCount() - 1; if ( image2DHeader.guid.empty() ) { @@ -162,32 +237,36 @@ namespace e57 if ( !image2DHeader.associatedData3DGuid.empty() ) { - image.set( "associatedData3DGuid", StringNode( imf_, image2DHeader.associatedData3DGuid ) ); + image.set( "associatedData3DGuid", + StringNode( imf_, image2DHeader.associatedData3DGuid ) ); } - if ( image2DHeader.acquisitionDateTime.dateTimeValue > 0. ) + if ( image2DHeader.acquisitionDateTime.dateTimeValue > 0.0 ) { - StructureNode acquisitionDateTime = StructureNode( imf_ ); + StructureNode acquisitionDateTime( imf_ ); + image.set( "acquisitionDateTime", acquisitionDateTime ); - acquisitionDateTime.set( "dateTimeValue", FloatNode( imf_, image2DHeader.acquisitionDateTime.dateTimeValue ) ); - acquisitionDateTime.set( "isAtomicClockReferenced", - IntegerNode( imf_, image2DHeader.acquisitionDateTime.isAtomicClockReferenced ) ); + acquisitionDateTime.set( + "dateTimeValue", FloatNode( imf_, image2DHeader.acquisitionDateTime.dateTimeValue ) ); + acquisitionDateTime.set( + "isAtomicClockReferenced", + IntegerNode( imf_, image2DHeader.acquisitionDateTime.isAtomicClockReferenced ) ); } // Create pose structure for image. if ( image2DHeader.pose != RigidBodyTransform{} ) { - StructureNode pose = StructureNode( imf_ ); + StructureNode pose( imf_ ); image.set( "pose", pose ); - StructureNode rotation = StructureNode( imf_ ); + StructureNode rotation( imf_ ); pose.set( "rotation", rotation ); rotation.set( "w", FloatNode( imf_, image2DHeader.pose.rotation.w ) ); rotation.set( "x", FloatNode( imf_, image2DHeader.pose.rotation.x ) ); rotation.set( "y", FloatNode( imf_, image2DHeader.pose.rotation.y ) ); rotation.set( "z", FloatNode( imf_, image2DHeader.pose.rotation.z ) ); - StructureNode translation = StructureNode( imf_ ); + StructureNode translation( imf_ ); pose.set( "translation", translation ); translation.set( "x", FloatNode( imf_, image2DHeader.pose.translation.x ) ); translation.set( "y", FloatNode( imf_, image2DHeader.pose.translation.y ) ); @@ -197,236 +276,216 @@ namespace e57 if ( image2DHeader.visualReferenceRepresentation.jpegImageSize > 0 || image2DHeader.visualReferenceRepresentation.pngImageSize > 0 ) { - StructureNode visualReferenceRepresentation = StructureNode( imf_ ); + StructureNode visualReferenceRepresentation( imf_ ); image.set( "visualReferenceRepresentation", visualReferenceRepresentation ); if ( image2DHeader.visualReferenceRepresentation.jpegImageSize > 0 ) { visualReferenceRepresentation.set( - "jpegImage", BlobNode( imf_, image2DHeader.visualReferenceRepresentation.jpegImageSize ) ); + "jpegImage", + BlobNode( imf_, image2DHeader.visualReferenceRepresentation.jpegImageSize ) ); } else if ( image2DHeader.visualReferenceRepresentation.pngImageSize > 0 ) { visualReferenceRepresentation.set( - "pngImage", BlobNode( imf_, image2DHeader.visualReferenceRepresentation.pngImageSize ) ); + "pngImage", + BlobNode( imf_, image2DHeader.visualReferenceRepresentation.pngImageSize ) ); } if ( image2DHeader.visualReferenceRepresentation.imageMaskSize > 0 ) { visualReferenceRepresentation.set( - "imageMask", BlobNode( imf_, image2DHeader.visualReferenceRepresentation.imageMaskSize ) ); + "imageMask", + BlobNode( imf_, image2DHeader.visualReferenceRepresentation.imageMaskSize ) ); } visualReferenceRepresentation.set( - "imageHeight", IntegerNode( imf_, image2DHeader.visualReferenceRepresentation.imageHeight ) ); + "imageHeight", + IntegerNode( imf_, image2DHeader.visualReferenceRepresentation.imageHeight ) ); visualReferenceRepresentation.set( - "imageWidth", IntegerNode( imf_, image2DHeader.visualReferenceRepresentation.imageWidth ) ); + "imageWidth", + IntegerNode( imf_, image2DHeader.visualReferenceRepresentation.imageWidth ) ); } else if ( image2DHeader.pinholeRepresentation.jpegImageSize > 0 || image2DHeader.pinholeRepresentation.pngImageSize > 0 ) { - StructureNode pinholeRepresentation = StructureNode( imf_ ); + StructureNode pinholeRepresentation( imf_ ); image.set( "pinholeRepresentation", pinholeRepresentation ); if ( image2DHeader.pinholeRepresentation.jpegImageSize > 0 ) { - pinholeRepresentation.set( "jpegImage", - BlobNode( imf_, image2DHeader.pinholeRepresentation.jpegImageSize ) ); + pinholeRepresentation.set( + "jpegImage", BlobNode( imf_, image2DHeader.pinholeRepresentation.jpegImageSize ) ); } else if ( image2DHeader.pinholeRepresentation.pngImageSize > 0 ) { - pinholeRepresentation.set( "pngImage", BlobNode( imf_, image2DHeader.pinholeRepresentation.pngImageSize ) ); + pinholeRepresentation.set( + "pngImage", BlobNode( imf_, image2DHeader.pinholeRepresentation.pngImageSize ) ); } if ( image2DHeader.pinholeRepresentation.imageMaskSize > 0 ) { - pinholeRepresentation.set( "imageMask", - BlobNode( imf_, image2DHeader.pinholeRepresentation.imageMaskSize ) ); + pinholeRepresentation.set( + "imageMask", BlobNode( imf_, image2DHeader.pinholeRepresentation.imageMaskSize ) ); } - pinholeRepresentation.set( "focalLength", FloatNode( imf_, image2DHeader.pinholeRepresentation.focalLength ) ); - pinholeRepresentation.set( "imageHeight", - IntegerNode( imf_, image2DHeader.pinholeRepresentation.imageHeight ) ); - pinholeRepresentation.set( "imageWidth", IntegerNode( imf_, image2DHeader.pinholeRepresentation.imageWidth ) ); - pinholeRepresentation.set( "pixelHeight", FloatNode( imf_, image2DHeader.pinholeRepresentation.pixelHeight ) ); - pinholeRepresentation.set( "pixelWidth", FloatNode( imf_, image2DHeader.pinholeRepresentation.pixelWidth ) ); - pinholeRepresentation.set( "principalPointX", - FloatNode( imf_, image2DHeader.pinholeRepresentation.principalPointX ) ); - pinholeRepresentation.set( "principalPointY", - FloatNode( imf_, image2DHeader.pinholeRepresentation.principalPointY ) ); + pinholeRepresentation.set( + "focalLength", FloatNode( imf_, image2DHeader.pinholeRepresentation.focalLength ) ); + pinholeRepresentation.set( + "imageHeight", IntegerNode( imf_, image2DHeader.pinholeRepresentation.imageHeight ) ); + pinholeRepresentation.set( + "imageWidth", IntegerNode( imf_, image2DHeader.pinholeRepresentation.imageWidth ) ); + pinholeRepresentation.set( + "pixelHeight", FloatNode( imf_, image2DHeader.pinholeRepresentation.pixelHeight ) ); + pinholeRepresentation.set( + "pixelWidth", FloatNode( imf_, image2DHeader.pinholeRepresentation.pixelWidth ) ); + pinholeRepresentation.set( + "principalPointX", + FloatNode( imf_, image2DHeader.pinholeRepresentation.principalPointX ) ); + pinholeRepresentation.set( + "principalPointY", + FloatNode( imf_, image2DHeader.pinholeRepresentation.principalPointY ) ); } else if ( image2DHeader.sphericalRepresentation.jpegImageSize > 0 || image2DHeader.sphericalRepresentation.pngImageSize > 0 ) { - StructureNode sphericalRepresentation = StructureNode( imf_ ); + StructureNode sphericalRepresentation( imf_ ); image.set( "sphericalRepresentation", sphericalRepresentation ); if ( image2DHeader.sphericalRepresentation.jpegImageSize > 0 ) { - sphericalRepresentation.set( "jpegImage", - BlobNode( imf_, image2DHeader.sphericalRepresentation.jpegImageSize ) ); + sphericalRepresentation.set( + "jpegImage", BlobNode( imf_, image2DHeader.sphericalRepresentation.jpegImageSize ) ); } else if ( image2DHeader.sphericalRepresentation.pngImageSize > 0 ) { - sphericalRepresentation.set( "pngImage", - BlobNode( imf_, image2DHeader.sphericalRepresentation.pngImageSize ) ); + sphericalRepresentation.set( + "pngImage", BlobNode( imf_, image2DHeader.sphericalRepresentation.pngImageSize ) ); } if ( image2DHeader.sphericalRepresentation.imageMaskSize > 0 ) { - sphericalRepresentation.set( "imageMask", - BlobNode( imf_, image2DHeader.sphericalRepresentation.imageMaskSize ) ); + sphericalRepresentation.set( + "imageMask", BlobNode( imf_, image2DHeader.sphericalRepresentation.imageMaskSize ) ); } - sphericalRepresentation.set( "imageHeight", - IntegerNode( imf_, image2DHeader.sphericalRepresentation.imageHeight ) ); - sphericalRepresentation.set( "imageWidth", - IntegerNode( imf_, image2DHeader.sphericalRepresentation.imageWidth ) ); - sphericalRepresentation.set( "pixelHeight", - FloatNode( imf_, image2DHeader.sphericalRepresentation.pixelHeight ) ); - sphericalRepresentation.set( "pixelWidth", - FloatNode( imf_, image2DHeader.sphericalRepresentation.pixelWidth ) ); + sphericalRepresentation.set( + "imageHeight", IntegerNode( imf_, image2DHeader.sphericalRepresentation.imageHeight ) ); + sphericalRepresentation.set( + "imageWidth", IntegerNode( imf_, image2DHeader.sphericalRepresentation.imageWidth ) ); + sphericalRepresentation.set( + "pixelHeight", FloatNode( imf_, image2DHeader.sphericalRepresentation.pixelHeight ) ); + sphericalRepresentation.set( + "pixelWidth", FloatNode( imf_, image2DHeader.sphericalRepresentation.pixelWidth ) ); } else if ( image2DHeader.cylindricalRepresentation.jpegImageSize > 0 || image2DHeader.cylindricalRepresentation.pngImageSize > 0 ) { - StructureNode cylindricalRepresentation = StructureNode( imf_ ); + StructureNode cylindricalRepresentation( imf_ ); image.set( "cylindricalRepresentation", cylindricalRepresentation ); if ( image2DHeader.cylindricalRepresentation.jpegImageSize > 0 ) { - cylindricalRepresentation.set( "jpegImage", - BlobNode( imf_, image2DHeader.cylindricalRepresentation.jpegImageSize ) ); + cylindricalRepresentation.set( + "jpegImage", + BlobNode( imf_, image2DHeader.cylindricalRepresentation.jpegImageSize ) ); } else if ( image2DHeader.cylindricalRepresentation.pngImageSize > 0 ) { - cylindricalRepresentation.set( "pngImage", - BlobNode( imf_, image2DHeader.cylindricalRepresentation.pngImageSize ) ); + cylindricalRepresentation.set( + "pngImage", BlobNode( imf_, image2DHeader.cylindricalRepresentation.pngImageSize ) ); } if ( image2DHeader.cylindricalRepresentation.imageMaskSize > 0 ) { - cylindricalRepresentation.set( "imageMask", - BlobNode( imf_, image2DHeader.cylindricalRepresentation.imageMaskSize ) ); + cylindricalRepresentation.set( + "imageMask", + BlobNode( imf_, image2DHeader.cylindricalRepresentation.imageMaskSize ) ); } - cylindricalRepresentation.set( "imageHeight", - IntegerNode( imf_, image2DHeader.cylindricalRepresentation.imageHeight ) ); - cylindricalRepresentation.set( "imageWidth", - IntegerNode( imf_, image2DHeader.cylindricalRepresentation.imageWidth ) ); - cylindricalRepresentation.set( "pixelHeight", - FloatNode( imf_, image2DHeader.cylindricalRepresentation.pixelHeight ) ); - cylindricalRepresentation.set( "pixelWidth", - FloatNode( imf_, image2DHeader.cylindricalRepresentation.pixelWidth ) ); - cylindricalRepresentation.set( "principalPointY", - FloatNode( imf_, image2DHeader.cylindricalRepresentation.principalPointY ) ); - cylindricalRepresentation.set( "radius", FloatNode( imf_, image2DHeader.cylindricalRepresentation.radius ) ); + cylindricalRepresentation.set( + "imageHeight", + IntegerNode( imf_, image2DHeader.cylindricalRepresentation.imageHeight ) ); + cylindricalRepresentation.set( + "imageWidth", IntegerNode( imf_, image2DHeader.cylindricalRepresentation.imageWidth ) ); + cylindricalRepresentation.set( + "pixelHeight", FloatNode( imf_, image2DHeader.cylindricalRepresentation.pixelHeight ) ); + cylindricalRepresentation.set( + "pixelWidth", FloatNode( imf_, image2DHeader.cylindricalRepresentation.pixelWidth ) ); + cylindricalRepresentation.set( + "principalPointY", + FloatNode( imf_, image2DHeader.cylindricalRepresentation.principalPointY ) ); + cylindricalRepresentation.set( + "radius", FloatNode( imf_, image2DHeader.cylindricalRepresentation.radius ) ); } return pos; } - // This function reads one of the image blobs - int64_t WriterImpl::WriteImage2DNode( StructureNode image, Image2DType imageType, void *pBuffer, int64_t start, - int64_t count ) - { - int64_t transferred = 0; - switch ( imageType ) - { - case E57_NO_IMAGE: - { - return 0; - } - case E57_JPEG_IMAGE: - { - if ( image.isDefined( "jpegImage" ) ) - { - BlobNode jpegImage( image.get( "jpegImage" ) ); - jpegImage.write( (uint8_t *)pBuffer, start, (size_t)count ); - transferred = count; - } - break; - } - case E57_PNG_IMAGE: - { - if ( image.isDefined( "pngImage" ) ) - { - BlobNode pngImage( image.get( "pngImage" ) ); - pngImage.write( (uint8_t *)pBuffer, start, (size_t)count ); - transferred = count; - } - break; - } - case E57_PNG_IMAGE_MASK: - { - if ( image.isDefined( "imageMask" ) ) - { - BlobNode imageMask( image.get( "imageMask" ) ); - imageMask.write( (uint8_t *)pBuffer, start, (size_t)count ); - transferred = count; - } - break; - } - } - return transferred; - } - - int64_t WriterImpl::WriteImage2DData( int64_t imageIndex, Image2DType imageType, Image2DProjection imageProjection, - void *pBuffer, int64_t start, int64_t count ) + size_t WriterImpl::WriteImage2DData( int64_t imageIndex, Image2DType imageType, + Image2DProjection imageProjection, uint8_t *pBuffer, + int64_t start, size_t count ) { if ( ( imageIndex < 0 ) || ( imageIndex >= images2D_.childCount() ) ) { return 0; } - int64_t transferred = 0; - StructureNode image( images2D_.get( imageIndex ) ); + const StructureNode image( images2D_.get( imageIndex ) ); switch ( imageProjection ) { - case E57_NO_PROJECTION: + case ProjectionNone: return 0; - case E57_VISUAL: + + case ProjectionVisual: if ( image.isDefined( "visualReferenceRepresentation" ) ) { - StructureNode visualReferenceRepresentation( image.get( "visualReferenceRepresentation" ) ); - transferred = WriteImage2DNode( visualReferenceRepresentation, imageType, pBuffer, start, count ); + StructureNode visualReferenceRepresentation( + image.get( "visualReferenceRepresentation" ) ); + return _writeImage2DNode( visualReferenceRepresentation, imageType, pBuffer, start, + count ); } break; - case E57_PINHOLE: + + case ProjectionPinhole: if ( image.isDefined( "pinholeRepresentation" ) ) { StructureNode pinholeRepresentation( image.get( "pinholeRepresentation" ) ); - transferred = WriteImage2DNode( pinholeRepresentation, imageType, pBuffer, start, count ); + return _writeImage2DNode( pinholeRepresentation, imageType, pBuffer, start, count ); } break; - case E57_SPHERICAL: + + case ProjectionSpherical: if ( image.isDefined( "sphericalRepresentation" ) ) { StructureNode sphericalRepresentation( image.get( "sphericalRepresentation" ) ); - transferred = WriteImage2DNode( sphericalRepresentation, imageType, pBuffer, start, count ); + return _writeImage2DNode( sphericalRepresentation, imageType, pBuffer, start, + count ); } break; - case E57_CYLINDRICAL: + + case ProjectionCylindrical: if ( image.isDefined( "cylindricalRepresentation" ) ) { StructureNode cylindricalRepresentation( image.get( "cylindricalRepresentation" ) ); - transferred = WriteImage2DNode( cylindricalRepresentation, imageType, pBuffer, start, count ); + return _writeImage2DNode( cylindricalRepresentation, imageType, pBuffer, start, + count ); } break; } - return transferred; + + return 0; } int64_t WriterImpl::NewData3D( Data3D &data3DHeader ) { - int64_t pos = -1; + StructureNode scan( imf_ ); + data3D_.append( scan ); + + int64_t pos = data3D_.childCount() - 1; if ( data3DHeader.guid.empty() ) { data3DHeader.guid = generateRandomGUID(); } - StructureNode scan = StructureNode( imf_ ); - data3D_.append( scan ); - pos = data3D_.childCount() - 1; - - scan.set( "guid", StringNode( imf_, data3DHeader.guid ) ); // required + scan.set( "guid", StringNode( imf_, data3DHeader.guid ) ); if ( !data3DHeader.name.empty() ) { @@ -438,14 +497,15 @@ namespace e57 scan.set( "description", StringNode( imf_, data3DHeader.description ) ); } - if ( data3DHeader.originalGuids.size() > 0 ) + if ( !data3DHeader.originalGuids.empty() ) { scan.set( "originalGuids", VectorNode( imf_ ) ); + VectorNode originalGuids( scan.get( "originalGuids" ) ); - int i; - for ( i = 0; i < (int)data3DHeader.originalGuids.size(); i++ ) + + for ( const auto &guid : data3DHeader.originalGuids ) { - originalGuids.append( StringNode( imf_, data3DHeader.originalGuids[i] ) ); + originalGuids.append( StringNode( imf_, guid ) ); } } @@ -455,138 +515,202 @@ namespace e57 { scan.set( "sensorVendor", StringNode( imf_, data3DHeader.sensorVendor ) ); } + if ( !data3DHeader.sensorModel.empty() ) { scan.set( "sensorModel", StringNode( imf_, data3DHeader.sensorModel ) ); } + if ( !data3DHeader.sensorSerialNumber.empty() ) { scan.set( "sensorSerialNumber", StringNode( imf_, data3DHeader.sensorSerialNumber ) ); } + if ( !data3DHeader.sensorHardwareVersion.empty() ) { - scan.set( "sensorHardwareVersion", StringNode( imf_, data3DHeader.sensorHardwareVersion ) ); + scan.set( "sensorHardwareVersion", + StringNode( imf_, data3DHeader.sensorHardwareVersion ) ); } + if ( !data3DHeader.sensorSoftwareVersion.empty() ) { - scan.set( "sensorSoftwareVersion", StringNode( imf_, data3DHeader.sensorSoftwareVersion ) ); + scan.set( "sensorSoftwareVersion", + StringNode( imf_, data3DHeader.sensorSoftwareVersion ) ); } + if ( !data3DHeader.sensorFirmwareVersion.empty() ) { - scan.set( "sensorFirmwareVersion", StringNode( imf_, data3DHeader.sensorFirmwareVersion ) ); + scan.set( "sensorFirmwareVersion", + StringNode( imf_, data3DHeader.sensorFirmwareVersion ) ); } // Add temp/humidity to scan. // Path names: "/data3D/0/temperature", etc... - if ( data3DHeader.temperature != E57_FLOAT_MAX ) + if ( data3DHeader.temperature != FLOAT_MAX ) { scan.set( "temperature", FloatNode( imf_, data3DHeader.temperature ) ); } - if ( data3DHeader.relativeHumidity != E57_FLOAT_MAX ) + if ( data3DHeader.relativeHumidity != FLOAT_MAX ) { scan.set( "relativeHumidity", FloatNode( imf_, data3DHeader.relativeHumidity ) ); } - if ( data3DHeader.atmosphericPressure != E57_FLOAT_MAX ) + if ( data3DHeader.atmosphericPressure != FLOAT_MAX ) { scan.set( "atmosphericPressure", FloatNode( imf_, data3DHeader.atmosphericPressure ) ); } if ( data3DHeader.indexBounds != IndexBounds{} ) { - StructureNode ibox = StructureNode( imf_ ); + StructureNode ibox( imf_ ); - if ( ( data3DHeader.indexBounds.rowMinimum != 0 ) || ( data3DHeader.indexBounds.rowMaximum != 0 ) ) + if ( ( data3DHeader.indexBounds.rowMinimum != 0 ) || + ( data3DHeader.indexBounds.rowMaximum != 0 ) ) { ibox.set( "rowMinimum", IntegerNode( imf_, data3DHeader.indexBounds.rowMinimum ) ); ibox.set( "rowMaximum", IntegerNode( imf_, data3DHeader.indexBounds.rowMaximum ) ); } - if ( ( data3DHeader.indexBounds.columnMinimum != 0 ) || ( data3DHeader.indexBounds.columnMaximum != 0 ) ) + + if ( ( data3DHeader.indexBounds.columnMinimum != 0 ) || + ( data3DHeader.indexBounds.columnMaximum != 0 ) ) { - ibox.set( "columnMinimum", IntegerNode( imf_, data3DHeader.indexBounds.columnMinimum ) ); - ibox.set( "columnMaximum", IntegerNode( imf_, data3DHeader.indexBounds.columnMaximum ) ); + ibox.set( "columnMinimum", + IntegerNode( imf_, data3DHeader.indexBounds.columnMinimum ) ); + ibox.set( "columnMaximum", + IntegerNode( imf_, data3DHeader.indexBounds.columnMaximum ) ); } - if ( ( data3DHeader.indexBounds.returnMinimum != 0 ) || ( data3DHeader.indexBounds.returnMaximum != 0 ) ) + + if ( ( data3DHeader.indexBounds.returnMinimum != 0 ) || + ( data3DHeader.indexBounds.returnMaximum != 0 ) ) { - ibox.set( "returnMinimum", IntegerNode( imf_, data3DHeader.indexBounds.returnMinimum ) ); - ibox.set( "returnMaximum", IntegerNode( imf_, data3DHeader.indexBounds.returnMaximum ) ); + ibox.set( "returnMinimum", + IntegerNode( imf_, data3DHeader.indexBounds.returnMinimum ) ); + ibox.set( "returnMaximum", + IntegerNode( imf_, data3DHeader.indexBounds.returnMaximum ) ); } + scan.set( "indexBounds", ibox ); } - if ( ( data3DHeader.intensityLimits.intensityMaximum != 0. ) || - ( data3DHeader.intensityLimits.intensityMinimum != 0. ) ) + if ( ( data3DHeader.intensityLimits.intensityMaximum != 0.0 ) || + ( data3DHeader.intensityLimits.intensityMinimum != 0.0 ) ) { - StructureNode intbox = StructureNode( imf_ ); - if ( data3DHeader.pointFields.intensityScaledInteger > 0. ) + StructureNode intbox( imf_ ); + + const double intensityMin = data3DHeader.intensityLimits.intensityMinimum; + const double intensityMax = data3DHeader.intensityLimits.intensityMaximum; + + switch ( data3DHeader.pointFields.intensityNodeType ) { - double offset = 0.; - double scale = data3DHeader.pointFields.intensityScaledInteger; + case NumericalNodeType::Integer: + { + intbox.set( "intensityMinimum", + IntegerNode( imf_, static_cast( intensityMin ) ) ); + intbox.set( "intensityMaximum", + IntegerNode( imf_, static_cast( intensityMax ) ) ); - int64_t rawIntegerMinimum = - (int64_t)floor( ( data3DHeader.intensityLimits.intensityMinimum - offset ) / scale + .5 ); - int64_t rawIntegerMaximum = - (int64_t)floor( ( data3DHeader.intensityLimits.intensityMaximum - offset ) / scale + .5 ); + break; + } - intbox.set( "intensityMaximum", ScaledIntegerNode( imf_, rawIntegerMaximum, rawIntegerMinimum, - rawIntegerMaximum, scale, offset ) ); + case NumericalNodeType::ScaledInteger: + { + const double scale = data3DHeader.pointFields.intensityScale; + const double offset = 0.0; + + const auto rawIntegerMinimum = + static_cast( std::floor( ( intensityMin - offset ) / scale + .5 ) ); + const auto rawIntegerMaximum = + static_cast( std::floor( ( intensityMax - offset ) / scale + .5 ) ); + + intbox.set( "intensityMinimum", + ScaledIntegerNode( imf_, rawIntegerMinimum, rawIntegerMinimum, + rawIntegerMaximum, scale, offset ) ); + intbox.set( "intensityMaximum", + ScaledIntegerNode( imf_, rawIntegerMaximum, rawIntegerMinimum, + rawIntegerMaximum, scale, offset ) ); + + break; + } - intbox.set( "intensityMinimum", ScaledIntegerNode( imf_, rawIntegerMinimum, rawIntegerMinimum, - rawIntegerMaximum, scale, offset ) ); - } - else if ( data3DHeader.pointFields.intensityScaledInteger == 0. ) - { - intbox.set( "intensityMaximum", FloatNode( imf_, data3DHeader.intensityLimits.intensityMaximum ) ); - intbox.set( "intensityMinimum", FloatNode( imf_, data3DHeader.intensityLimits.intensityMinimum ) ); - } - else - { - intbox.set( "intensityMaximum", - IntegerNode( imf_, (int64_t)data3DHeader.intensityLimits.intensityMaximum ) ); - intbox.set( "intensityMinimum", - IntegerNode( imf_, (int64_t)data3DHeader.intensityLimits.intensityMinimum ) ); + case NumericalNodeType::Float: + { + intbox.set( "intensityMinimum", FloatNode( imf_, intensityMin, PrecisionSingle ) ); + intbox.set( "intensityMaximum", FloatNode( imf_, intensityMax, PrecisionSingle ) ); + + break; + } + + case NumericalNodeType::Double: + { + intbox.set( "intensityMinimum", FloatNode( imf_, intensityMin, PrecisionDouble ) ); + intbox.set( "intensityMaximum", FloatNode( imf_, intensityMax, PrecisionDouble ) ); + + break; + } } + scan.set( "intensityLimits", intbox ); } - if ( ( data3DHeader.colorLimits.colorRedMaximum != 0. ) || ( data3DHeader.colorLimits.colorRedMinimum != 0. ) ) - { - StructureNode colorbox = StructureNode( imf_ ); - colorbox.set( "colorRedMaximum", IntegerNode( imf_, (int64_t)data3DHeader.colorLimits.colorRedMaximum ) ); - colorbox.set( "colorRedMinimum", IntegerNode( imf_, (int64_t)data3DHeader.colorLimits.colorRedMinimum ) ); - colorbox.set( "colorGreenMaximum", IntegerNode( imf_, (int64_t)data3DHeader.colorLimits.colorGreenMaximum ) ); - colorbox.set( "colorGreenMinimum", IntegerNode( imf_, (int64_t)data3DHeader.colorLimits.colorGreenMinimum ) ); - colorbox.set( "colorBlueMaximum", IntegerNode( imf_, (int64_t)data3DHeader.colorLimits.colorBlueMaximum ) ); - colorbox.set( "colorBlueMinimum", IntegerNode( imf_, (int64_t)data3DHeader.colorLimits.colorBlueMinimum ) ); + if ( ( data3DHeader.colorLimits.colorRedMaximum != 0.0 ) || + ( data3DHeader.colorLimits.colorRedMinimum != 0.0 ) ) + { + StructureNode colorbox( imf_ ); + + colorbox.set( + "colorRedMaximum", + IntegerNode( imf_, static_cast( data3DHeader.colorLimits.colorRedMaximum ) ) ); + colorbox.set( + "colorRedMinimum", + IntegerNode( imf_, static_cast( data3DHeader.colorLimits.colorRedMinimum ) ) ); + colorbox.set( "colorGreenMaximum", + IntegerNode( imf_, static_cast( + data3DHeader.colorLimits.colorGreenMaximum ) ) ); + colorbox.set( "colorGreenMinimum", + IntegerNode( imf_, static_cast( + data3DHeader.colorLimits.colorGreenMinimum ) ) ); + colorbox.set( "colorBlueMaximum", + IntegerNode( imf_, static_cast( + data3DHeader.colorLimits.colorBlueMaximum ) ) ); + colorbox.set( "colorBlueMinimum", + IntegerNode( imf_, static_cast( + data3DHeader.colorLimits.colorBlueMinimum ) ) ); + scan.set( "colorLimits", colorbox ); } // Add Cartesian bounding box to scan. // Path names: "/data3D/0/cartesianBounds/xMinimum", etc... - if ( ( data3DHeader.cartesianBounds.xMinimum != -E57_DOUBLE_MAX ) || - ( data3DHeader.cartesianBounds.xMaximum != E57_DOUBLE_MAX ) ) + if ( ( data3DHeader.cartesianBounds.xMinimum != -DOUBLE_MAX ) || + ( data3DHeader.cartesianBounds.xMaximum != DOUBLE_MAX ) ) { - StructureNode bbox = StructureNode( imf_ ); + StructureNode bbox( imf_ ); + bbox.set( "xMinimum", FloatNode( imf_, data3DHeader.cartesianBounds.xMinimum ) ); bbox.set( "xMaximum", FloatNode( imf_, data3DHeader.cartesianBounds.xMaximum ) ); bbox.set( "yMinimum", FloatNode( imf_, data3DHeader.cartesianBounds.yMinimum ) ); bbox.set( "yMaximum", FloatNode( imf_, data3DHeader.cartesianBounds.yMaximum ) ); bbox.set( "zMinimum", FloatNode( imf_, data3DHeader.cartesianBounds.zMinimum ) ); bbox.set( "zMaximum", FloatNode( imf_, data3DHeader.cartesianBounds.zMaximum ) ); + scan.set( "cartesianBounds", bbox ); } - if ( ( data3DHeader.sphericalBounds.rangeMinimum != 0. ) || - ( data3DHeader.sphericalBounds.rangeMaximum != E57_DOUBLE_MAX ) ) + if ( ( data3DHeader.sphericalBounds.rangeMinimum != 0.0 ) || + ( data3DHeader.sphericalBounds.rangeMaximum != DOUBLE_MAX ) ) { - StructureNode sbox = StructureNode( imf_ ); + StructureNode sbox( imf_ ); + sbox.set( "rangeMinimum", FloatNode( imf_, data3DHeader.sphericalBounds.rangeMinimum ) ); sbox.set( "rangeMaximum", FloatNode( imf_, data3DHeader.sphericalBounds.rangeMaximum ) ); - sbox.set( "elevationMinimum", FloatNode( imf_, data3DHeader.sphericalBounds.elevationMinimum ) ); - sbox.set( "elevationMaximum", FloatNode( imf_, data3DHeader.sphericalBounds.elevationMaximum ) ); + sbox.set( "elevationMinimum", + FloatNode( imf_, data3DHeader.sphericalBounds.elevationMinimum ) ); + sbox.set( "elevationMaximum", + FloatNode( imf_, data3DHeader.sphericalBounds.elevationMaximum ) ); sbox.set( "azimuthStart", FloatNode( imf_, data3DHeader.sphericalBounds.azimuthStart ) ); sbox.set( "azimuthEnd", FloatNode( imf_, data3DHeader.sphericalBounds.azimuthEnd ) ); + scan.set( "sphericalBounds", sbox ); } @@ -595,58 +719,65 @@ namespace e57 // "/data3D/0/pose/translation/x", etc... if ( data3DHeader.pose != RigidBodyTransform{} ) { - StructureNode pose = StructureNode( imf_ ); - scan.set( "pose", pose ); + StructureNode pose( imf_ ); - StructureNode rotation = StructureNode( imf_ ); + StructureNode rotation( imf_ ); rotation.set( "w", FloatNode( imf_, data3DHeader.pose.rotation.w ) ); rotation.set( "x", FloatNode( imf_, data3DHeader.pose.rotation.x ) ); rotation.set( "y", FloatNode( imf_, data3DHeader.pose.rotation.y ) ); rotation.set( "z", FloatNode( imf_, data3DHeader.pose.rotation.z ) ); pose.set( "rotation", rotation ); - StructureNode translation = StructureNode( imf_ ); + StructureNode translation( imf_ ); translation.set( "x", FloatNode( imf_, data3DHeader.pose.translation.x ) ); translation.set( "y", FloatNode( imf_, data3DHeader.pose.translation.y ) ); translation.set( "z", FloatNode( imf_, data3DHeader.pose.translation.z ) ); pose.set( "translation", translation ); + + scan.set( "pose", pose ); } // Add start/stop acquisition times to scan. // Path names: "/data3D/0/acquisitionStart/dateTimeValue", // "/data3D/0/acquisitionEnd/dateTimeValue" - if ( data3DHeader.acquisitionStart.dateTimeValue > 0. ) + if ( data3DHeader.acquisitionStart.dateTimeValue > 0.0 ) { - StructureNode acquisitionStart = StructureNode( imf_ ); + StructureNode acquisitionStart( imf_ ); + + acquisitionStart.set( "dateTimeValue", + FloatNode( imf_, data3DHeader.acquisitionStart.dateTimeValue ) ); + acquisitionStart.set( + "isAtomicClockReferenced", + IntegerNode( imf_, data3DHeader.acquisitionStart.isAtomicClockReferenced ) ); + scan.set( "acquisitionStart", acquisitionStart ); - acquisitionStart.set( "dateTimeValue", FloatNode( imf_, data3DHeader.acquisitionStart.dateTimeValue ) ); - acquisitionStart.set( "isAtomicClockReferenced", - IntegerNode( imf_, data3DHeader.acquisitionStart.isAtomicClockReferenced ) ); } - if ( data3DHeader.acquisitionEnd.dateTimeValue > 0. ) + if ( data3DHeader.acquisitionEnd.dateTimeValue > 0.0 ) { - StructureNode acquisitionEnd = StructureNode( imf_ ); + StructureNode acquisitionEnd( imf_ ); + + acquisitionEnd.set( "dateTimeValue", + FloatNode( imf_, data3DHeader.acquisitionEnd.dateTimeValue ) ); + acquisitionEnd.set( + "isAtomicClockReferenced", + IntegerNode( imf_, data3DHeader.acquisitionEnd.isAtomicClockReferenced ) ); + scan.set( "acquisitionEnd", acquisitionEnd ); - acquisitionEnd.set( "dateTimeValue", FloatNode( imf_, data3DHeader.acquisitionEnd.dateTimeValue ) ); - acquisitionEnd.set( "isAtomicClockReferenced", - IntegerNode( imf_, data3DHeader.acquisitionEnd.isAtomicClockReferenced ) ); } // Add grouping scheme area // Path name: "/data3D/0/pointGroupingSchemes" if ( !data3DHeader.pointGroupingSchemes.groupingByLine.idElementName.empty() ) { - StructureNode pointGroupingSchemes = StructureNode( imf_ ); - scan.set( "pointGroupingSchemes", pointGroupingSchemes ); + StructureNode pointGroupingSchemes( imf_ ); // Add a line grouping scheme // Path name: "/data3D/0/pointGroupingSchemes/groupingByLine" - StructureNode groupingByLine = StructureNode( imf_ ); - pointGroupingSchemes.set( "groupingByLine", groupingByLine ); + StructureNode groupingByLine( imf_ ); // data3DHeader.pointGroupingSchemes.groupingByLine.idElementName)); bool byColumn = true; // default should be "columnIndex" - if ( data3DHeader.pointGroupingSchemes.groupingByLine.idElementName.compare( "rowIndex" ) == 0 ) + if ( data3DHeader.pointGroupingSchemes.groupingByLine.idElementName == "rowIndex" ) { byColumn = false; } @@ -666,90 +797,91 @@ namespace e57 // This prototype will be used in creating the groups CompressedVector. // Will define path names like: // "/data3D/0/pointGroupingSchemes/groupingByLine/groups/0/idElementValue" - int64_t groupsSize = data3DHeader.pointGroupingSchemes.groupingByLine.groupsSize; - int64_t countSize = data3DHeader.pointGroupingSchemes.groupingByLine.pointCountSize; - int64_t pointsSize = data3DHeader.pointsSize; + const int64_t groupsSize = data3DHeader.pointGroupingSchemes.groupingByLine.groupsSize; + const int64_t countSize = data3DHeader.pointGroupingSchemes.groupingByLine.pointCountSize; + const int64_t pointsCount = data3DHeader.pointCount; - StructureNode lineGroupProto = StructureNode( imf_ ); - lineGroupProto.set( "startPointIndex", IntegerNode( imf_, 0, 0, pointsSize - 1 ) ); + StructureNode lineGroupProto( imf_ ); + + lineGroupProto.set( "startPointIndex", IntegerNode( imf_, 0, 0, pointsCount - 1 ) ); lineGroupProto.set( "idElementValue", IntegerNode( imf_, 0, 0, groupsSize - 1 ) ); lineGroupProto.set( "pointCount", IntegerNode( imf_, 0, 0, countSize ) ); - // Not supported in this Simple API for now - /* - StructureNode bbox = StructureNode(imf_); - bbox.set("xMinimum", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.pointRangeMinimum, data3DHeader.pointFields.pointRangeMaximum)); - bbox.set("xMaximum", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.pointRangeMinimum, data3DHeader.pointFields.pointRangeMaximum)); - bbox.set("yMinimum", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.pointRangeMinimum, data3DHeader.pointFields.pointRangeMaximum)); - bbox.set("yMaximum", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.pointRangeMinimum, data3DHeader.pointFields.pointRangeMaximum)); - bbox.set("zMinimum", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.pointRangeMinimum, data3DHeader.pointFields.pointRangeMaximum)); - bbox.set("zMaximum", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.pointRangeMinimum, data3DHeader.pointFields.pointRangeMaximum)); - lineGroupProto.set("cartesianBounds", bbox); - - StructureNode sbox = StructureNode(imf_); - sbox.set("rangeMinimum", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.pointRangeMinimum, data3DHeader.pointFields.pointRangeMaximum)); - sbox.set("rangeMaximum", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.pointRangeMinimum, data3DHeader.pointFields.pointRangeMaximum)); - sbox.set("elevationMinimum", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.angleMinimum, data3DHeader.pointFields.angleMaximum)); - sbox.set("elevationMaximum", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.angleMinimum, data3DHeader.pointFields.angleMaximum)); - sbox.set("azimuthStart", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.angleMinimum, data3DHeader.pointFields.angleMaximum)); - sbox.set("azimuthEnd", FloatNode(imf_, 0., E57_SINGLE, - data3DHeader.pointFields.angleMinimum, data3DHeader.pointFields.angleMaximum)); - lineGroupProto.set("sphericalBounds", sbox); - */ // Make empty codecs vector for use in creating groups CompressedVector. // If this vector is empty, it is assumed that all fields will use the BitPack codec. - VectorNode lineGroupCodecs = VectorNode( imf_, true ); + const VectorNode lineGroupCodecs( imf_, true ); // Create CompressedVector for storing groups. // Path Name: "/data3D/0/pointGroupingSchemes/groupingByLine/groups". // We use the prototype and empty codecs tree from above. // The CompressedVector will be filled by code below. - CompressedVectorNode groups = CompressedVectorNode( imf_, lineGroupProto, lineGroupCodecs ); + const CompressedVectorNode groups( imf_, lineGroupProto, lineGroupCodecs ); + groupingByLine.set( "groups", groups ); + pointGroupingSchemes.set( "groupingByLine", groupingByLine ); + scan.set( "pointGroupingSchemes", pointGroupingSchemes ); } // Make a prototype of datatypes that will be stored in points record. // This prototype will be used in creating the points CompressedVector. // Using this proto in a CompressedVector will define path names like: // "/data3D/0/points/0/cartesianX" - StructureNode proto = StructureNode( imf_ ); + StructureNode proto( imf_ ); - // Because ScaledInteger min/max are the raw integer min/max, we must calculate them from the data min/max - const double pointRangeScale = data3DHeader.pointFields.pointRangeScaledInteger; - const double pointRangeOffset = 0.; - int64_t pointRangeMinimum = - (int64_t)floor( ( data3DHeader.pointFields.pointRangeMinimum - pointRangeOffset ) / pointRangeScale + .5 ); - int64_t pointRangeMaximum = - (int64_t)floor( ( data3DHeader.pointFields.pointRangeMaximum - pointRangeOffset ) / pointRangeScale + .5 ); + const double pointRangeMin = data3DHeader.pointFields.pointRangeMinimum; + const double pointRangeMax = data3DHeader.pointFields.pointRangeMaximum; const auto getPointProto = [=]() -> Node { - if ( pointRangeScale > E57_NOT_SCALED_USE_FLOAT ) - { - return ScaledIntegerNode( imf_, 0, pointRangeMinimum, pointRangeMaximum, pointRangeScale, - pointRangeOffset ); - } - else + switch ( data3DHeader.pointFields.pointRangeNodeType ) { - return FloatNode( imf_, 0., ( pointRangeScale < E57_NOT_SCALED_USE_FLOAT ) ? E57_DOUBLE : E57_SINGLE, - data3DHeader.pointFields.pointRangeMinimum, data3DHeader.pointFields.pointRangeMaximum ); + case NumericalNodeType::Integer: + { + throw E57_EXCEPTION2( ErrorInvalidNodeType, "pointRangeNodeType cannot be Integer" ); + } + + case NumericalNodeType::ScaledInteger: + { + // Because ScaledInteger min/max are the raw integer min/max, we must calculate them + // from the data min/max + const double pointRangeOffset = 0.0; + const double pointRangeScale = data3DHeader.pointFields.pointRangeScale; + + if ( pointRangeScale == 0.0 ) + { + throw E57_EXCEPTION2( ErrorInvalidData3DValue, "pointRangeScale cannot be 0" ); + } + + const auto pointRangeMinimum = static_cast( + std::floor( ( pointRangeMin - pointRangeOffset ) / pointRangeScale + .5 ) ); + const auto pointRangeMaximum = static_cast( + std::floor( ( pointRangeMax - pointRangeOffset ) / pointRangeScale + .5 ) ); + + return ScaledIntegerNode( imf_, 0, pointRangeMinimum, pointRangeMaximum, + pointRangeScale, pointRangeOffset ); + } + + case NumericalNodeType::Float: + { + return FloatNode( imf_, 0.0, PrecisionSingle, pointRangeMin, pointRangeMax ); + } + + case NumericalNodeType::Double: + { + return FloatNode( imf_, 0.0, PrecisionDouble, pointRangeMin, pointRangeMax ); + } } + + throw E57_EXCEPTION2( + ErrorInvalidNodeType, + std::string( "Invalid pointRangeNodeType type: " ) + .append( _numericalNodeTypeStr( data3DHeader.pointFields.pointRangeNodeType ) ) ); }; if ( data3DHeader.pointFields.cartesianXField ) { proto.set( "cartesianX", getPointProto() ); } + if ( data3DHeader.pointFields.cartesianYField ) { proto.set( "cartesianY", getPointProto() ); @@ -765,23 +897,51 @@ namespace e57 proto.set( "sphericalRange", getPointProto() ); } - const double angleScale = data3DHeader.pointFields.angleScaledInteger; - const double angleOffset = 0.; - int64_t angleMinimum = - (int64_t)std::floor( ( data3DHeader.pointFields.angleMinimum - angleOffset ) / angleScale + .5 ); - int64_t angleMaximum = - (int64_t)std::floor( ( data3DHeader.pointFields.angleMaximum - angleOffset ) / angleScale + .5 ); + const double angleMin = data3DHeader.pointFields.angleMinimum; + const double angleMax = data3DHeader.pointFields.angleMaximum; const auto getAngleProto = [=]() -> Node { - if ( angleScale > E57_NOT_SCALED_USE_FLOAT ) + switch ( data3DHeader.pointFields.angleNodeType ) { - return ScaledIntegerNode( imf_, 0, angleMinimum, angleMaximum, angleScale, angleOffset ); - } - else - { - return FloatNode( imf_, 0., ( angleScale < E57_NOT_SCALED_USE_FLOAT ) ? E57_DOUBLE : E57_SINGLE, - data3DHeader.pointFields.angleMinimum, data3DHeader.pointFields.angleMaximum ); + case NumericalNodeType::Integer: + { + throw E57_EXCEPTION2( ErrorInvalidNodeType, "angleNodeType cannot be Integer" ); + } + + case NumericalNodeType::ScaledInteger: + { + const double angleOffset = 0.0; + const double angleScale = data3DHeader.pointFields.angleScale; + + if ( angleScale == 0.0 ) + { + throw E57_EXCEPTION2( ErrorInvalidData3DValue, "angleScale cannot be 0" ); + } + + const auto angleMinimum = static_cast( + std::floor( ( angleMin - angleOffset ) / angleScale + .5 ) ); + const auto angleMaximum = static_cast( + std::floor( ( angleMax - angleOffset ) / angleScale + .5 ) ); + + return ScaledIntegerNode( imf_, 0, angleMinimum, angleMaximum, angleScale, + angleOffset ); + } + + case NumericalNodeType::Float: + { + return FloatNode( imf_, 0.0, PrecisionSingle, angleMin, angleMax ); + } + + case NumericalNodeType::Double: + { + return FloatNode( imf_, 0.0, PrecisionDouble, angleMin, angleMax ); + } } + + throw E57_EXCEPTION2( + ErrorInvalidNodeType, + std::string( "Invalid angleNodeType type: " ) + .append( _numericalNodeTypeStr( data3DHeader.pointFields.angleNodeType ) ) ); }; if ( data3DHeader.pointFields.sphericalAzimuthField ) @@ -796,90 +956,141 @@ namespace e57 if ( data3DHeader.pointFields.intensityField ) { - if ( data3DHeader.pointFields.intensityScaledInteger > 0. ) - { - double offset = 0; // could be data3DHeader.intensityLimits.intensityMinimum; - double scale = data3DHeader.pointFields.intensityScaledInteger; - int64_t rawIntegerMinimum = - (int64_t)floor( ( data3DHeader.intensityLimits.intensityMinimum - offset ) / scale + .5 ); - int64_t rawIntegerMaximum = - (int64_t)floor( ( data3DHeader.intensityLimits.intensityMaximum - offset ) / scale + .5 ); - proto.set( "intensity", ScaledIntegerNode( imf_, 0, rawIntegerMinimum, rawIntegerMaximum, scale, offset ) ); - } - else if ( data3DHeader.pointFields.intensityScaledInteger == E57_NOT_SCALED_USE_FLOAT ) - { - proto.set( "intensity", FloatNode( imf_, 0., E57_SINGLE, data3DHeader.intensityLimits.intensityMinimum, - data3DHeader.intensityLimits.intensityMaximum ) ); - } - else + const double intensityMin = data3DHeader.intensityLimits.intensityMinimum; + const double intensityMax = data3DHeader.intensityLimits.intensityMaximum; + + switch ( data3DHeader.pointFields.intensityNodeType ) { - proto.set( "intensity", IntegerNode( imf_, 0, (int64_t)data3DHeader.intensityLimits.intensityMinimum, - (int64_t)data3DHeader.intensityLimits.intensityMaximum ) ); + case NumericalNodeType::Integer: + { + proto.set( "intensity", IntegerNode( imf_, 0, static_cast( intensityMin ), + static_cast( intensityMax ) ) ); + + break; + } + + case NumericalNodeType::ScaledInteger: + { + const double scale = data3DHeader.pointFields.intensityScale; + const double offset = 0.0; // could be data3DHeader.intensityLimits.intensityMinimum; + + const auto rawIntegerMaximum = + static_cast( std::floor( ( intensityMax - offset ) / scale + .5 ) ); + const auto rawIntegerMinimum = + static_cast( std::floor( ( intensityMin - offset ) / scale + .5 ) ); + + proto.set( "intensity", ScaledIntegerNode( imf_, 0, rawIntegerMinimum, + rawIntegerMaximum, scale, offset ) ); + + break; + } + + case NumericalNodeType::Float: + { + proto.set( "intensity", FloatNode( imf_, 0.0, PrecisionSingle, + data3DHeader.intensityLimits.intensityMinimum, + data3DHeader.intensityLimits.intensityMaximum ) ); + + break; + } + + case NumericalNodeType::Double: + { + proto.set( "intensity", FloatNode( imf_, 0.0, PrecisionDouble, + data3DHeader.intensityLimits.intensityMinimum, + data3DHeader.intensityLimits.intensityMaximum ) ); + + break; + } } } if ( data3DHeader.pointFields.colorRedField ) { - proto.set( "colorRed", IntegerNode( imf_, 0, (int64_t)data3DHeader.colorLimits.colorRedMinimum, - (int64_t)data3DHeader.colorLimits.colorRedMaximum ) ); + proto.set( + "colorRed", + IntegerNode( imf_, 0, static_cast( data3DHeader.colorLimits.colorRedMinimum ), + static_cast( data3DHeader.colorLimits.colorRedMaximum ) ) ); } if ( data3DHeader.pointFields.colorGreenField ) { - proto.set( "colorGreen", IntegerNode( imf_, 0, (int64_t)data3DHeader.colorLimits.colorGreenMinimum, - (int64_t)data3DHeader.colorLimits.colorGreenMaximum ) ); + proto.set( "colorGreen", + IntegerNode( + imf_, 0, static_cast( data3DHeader.colorLimits.colorGreenMinimum ), + static_cast( data3DHeader.colorLimits.colorGreenMaximum ) ) ); } if ( data3DHeader.pointFields.colorBlueField ) { - proto.set( "colorBlue", IntegerNode( imf_, 0, (int64_t)data3DHeader.colorLimits.colorBlueMinimum, - (int64_t)data3DHeader.colorLimits.colorBlueMaximum ) ); + proto.set( + "colorBlue", + IntegerNode( imf_, 0, static_cast( data3DHeader.colorLimits.colorBlueMinimum ), + static_cast( data3DHeader.colorLimits.colorBlueMaximum ) ) ); } if ( data3DHeader.pointFields.returnIndexField ) { - proto.set( "returnIndex", IntegerNode( imf_, 0, E57_UINT8_MIN, data3DHeader.pointFields.returnMaximum ) ); + proto.set( "returnIndex", + IntegerNode( imf_, 0, UINT8_MIN, data3DHeader.pointFields.returnMaximum ) ); } if ( data3DHeader.pointFields.returnCountField ) { - proto.set( "returnCount", IntegerNode( imf_, 0, E57_UINT8_MIN, data3DHeader.pointFields.returnMaximum ) ); + proto.set( "returnCount", + IntegerNode( imf_, 0, UINT8_MIN, data3DHeader.pointFields.returnMaximum ) ); } if ( data3DHeader.pointFields.rowIndexField ) { - proto.set( "rowIndex", IntegerNode( imf_, 0, E57_UINT32_MIN, data3DHeader.pointFields.rowIndexMaximum ) ); + proto.set( "rowIndex", + IntegerNode( imf_, 0, UINT32_MIN, data3DHeader.pointFields.rowIndexMaximum ) ); } if ( data3DHeader.pointFields.columnIndexField ) { - proto.set( "columnIndex", - IntegerNode( imf_, 0, E57_UINT32_MIN, data3DHeader.pointFields.columnIndexMaximum ) ); + proto.set( "columnIndex", IntegerNode( imf_, 0, UINT32_MIN, + data3DHeader.pointFields.columnIndexMaximum ) ); } if ( data3DHeader.pointFields.timeStampField ) { - if ( data3DHeader.pointFields.timeScaledInteger > 0. ) - { - double offset = 0; - double scale = data3DHeader.pointFields.timeScaledInteger; - int64_t rawIntegerMinimum = - (int64_t)floor( ( data3DHeader.pointFields.timeMinimum - offset ) / scale + .5 ); - int64_t rawIntegerMaximum = - (int64_t)floor( ( data3DHeader.pointFields.timeMaximum - offset ) / scale + .5 ); - proto.set( "timeStamp", ScaledIntegerNode( imf_, 0, rawIntegerMinimum, rawIntegerMaximum, scale, offset ) ); - } - else if ( data3DHeader.pointFields.timeScaledInteger == E57_NOT_SCALED_USE_FLOAT ) + const double timeMinimum = data3DHeader.pointFields.timeMinimum; + const double timeMaximum = data3DHeader.pointFields.timeMaximum; + + switch ( data3DHeader.pointFields.timeNodeType ) { - if ( data3DHeader.pointFields.timeMaximum == E57_FLOAT_MAX ) + case NumericalNodeType::Integer: { - proto.set( "timeStamp", FloatNode( imf_, 0., E57_SINGLE, E57_FLOAT_MIN, E57_FLOAT_MAX ) ); + proto.set( "timeStamp", IntegerNode( imf_, 0, static_cast( timeMinimum ), + static_cast( timeMaximum ) ) ); + break; } - else if ( data3DHeader.pointFields.timeMaximum == E57_DOUBLE_MAX ) + + case NumericalNodeType::ScaledInteger: { - proto.set( "timeStamp", FloatNode( imf_, 0., E57_DOUBLE, E57_DOUBLE_MIN, E57_DOUBLE_MAX ) ); + const double scale = data3DHeader.pointFields.timeScale; + const double offset = 0.0; + + const auto rawIntegerMinimum = + static_cast( std::floor( ( timeMinimum - offset ) / scale + .5 ) ); + const auto rawIntegerMaximum = + static_cast( std::floor( ( timeMaximum - offset ) / scale + .5 ) ); + + proto.set( "timeStamp", ScaledIntegerNode( imf_, 0, rawIntegerMinimum, + rawIntegerMaximum, scale, offset ) ); + break; + } + + case NumericalNodeType::Float: + { + proto.set( "timeStamp", + FloatNode( imf_, 0.0, PrecisionSingle, FLOAT_MIN, FLOAT_MAX ) ); + break; + } + + case NumericalNodeType::Double: + { + proto.set( "timeStamp", + FloatNode( imf_, 0.0, PrecisionDouble, DOUBLE_MIN, DOUBLE_MAX ) ); + break; } - } - else - { - proto.set( "timeStamp", IntegerNode( imf_, 0, (int64_t)data3DHeader.pointFields.timeMinimum, - (int64_t)data3DHeader.pointFields.timeMaximum ) ); } } @@ -905,152 +1116,179 @@ namespace e57 } // E57_EXT_surface_normals - if ( data3DHeader.pointFields.normalX || data3DHeader.pointFields.normalY || data3DHeader.pointFields.normalZ ) + // See: http://www.libe57.org/E57_EXT_surface_normals.txt + if ( data3DHeader.pointFields.normalXField || data3DHeader.pointFields.normalYField || + data3DHeader.pointFields.normalZField ) { // make sure we declare the extension before using the fields with prefix - ustring norExtUri; - if ( !imf_.extensionsLookupPrefix( "nor", norExtUri ) ) + if ( !imf_.extensionsLookupPrefix( "nor" ) ) { - imf_.extensionsAdd( "nor", "http://www.libe57.org/E57_NOR_surface_normals.txt" ); + imf_.extensionsAdd( "nor", "http://www.libe57.org/E57_EXT_surface_normals.txt" ); } } // currently we support writing normals only as float32 - if ( data3DHeader.pointFields.normalX ) + if ( data3DHeader.pointFields.normalXField ) { - proto.set( "nor:normalX", FloatNode( imf_, 0., E57_SINGLE, -1., 1. ) ); + proto.set( "nor:normalX", FloatNode( imf_, 0.0, PrecisionSingle, -1.0, 1.0 ) ); } - if ( data3DHeader.pointFields.normalY ) + if ( data3DHeader.pointFields.normalYField ) { - proto.set( "nor:normalY", FloatNode( imf_, 0., E57_SINGLE, -1., 1. ) ); + proto.set( "nor:normalY", FloatNode( imf_, 0.0, PrecisionSingle, -1.0, 1.0 ) ); } - if ( data3DHeader.pointFields.normalZ ) + if ( data3DHeader.pointFields.normalZField ) { - proto.set( "nor:normalZ", FloatNode( imf_, 0., E57_SINGLE, -1., 1. ) ); + proto.set( "nor:normalZ", FloatNode( imf_, 0.0, PrecisionSingle, -1.0, 1.0 ) ); } // Make empty codecs vector for use in creating points CompressedVector. // If this vector is empty, it is assumed that all fields will use the BitPack codec. - VectorNode codecs = VectorNode( imf_, true ); + const VectorNode codecs( imf_, true ); // Create CompressedVector for storing points. Path Name: "/data3D/0/points". // We use the prototype and empty codecs tree from above. // The CompressedVector will be filled by code below. - CompressedVectorNode points = CompressedVectorNode( imf_, proto, codecs ); + const CompressedVectorNode points( imf_, proto, codecs ); + scan.set( "points", points ); + return pos; } template - CompressedVectorWriter WriterImpl::SetUpData3DPointsData( int64_t dataIndex, size_t count, - const Data3DPointsData_t &buffers ) + CompressedVectorWriter WriterImpl::SetUpData3DPointsData( + int64_t dataIndex, size_t count, const Data3DPointsData_t &buffers ) { - StructureNode scan( data3D_.get( dataIndex ) ); - CompressedVectorNode points( scan.get( "points" ) ); - StructureNode proto( points.prototype() ); + static_assert( std::is_floating_point::value, "Floating point type required." ); + const StructureNode scan( data3D_.get( dataIndex ) ); + CompressedVectorNode points( scan.get( "points" ) ); + const StructureNode proto( points.prototype() ); std::vector sourceBuffers; - if ( proto.isDefined( "cartesianX" ) && buffers.cartesianX ) + + if ( proto.isDefined( "cartesianX" ) && ( buffers.cartesianX != nullptr ) ) { sourceBuffers.emplace_back( imf_, "cartesianX", buffers.cartesianX, count, true, true ); } - if ( proto.isDefined( "cartesianY" ) && buffers.cartesianY ) + + if ( proto.isDefined( "cartesianY" ) && ( buffers.cartesianY != nullptr ) ) { sourceBuffers.emplace_back( imf_, "cartesianY", buffers.cartesianY, count, true, true ); } - if ( proto.isDefined( "cartesianZ" ) && buffers.cartesianZ ) + + if ( proto.isDefined( "cartesianZ" ) && ( buffers.cartesianZ != nullptr ) ) { sourceBuffers.emplace_back( imf_, "cartesianZ", buffers.cartesianZ, count, true, true ); } - if ( proto.isDefined( "sphericalRange" ) && buffers.sphericalRange ) + if ( proto.isDefined( "sphericalRange" ) && ( buffers.sphericalRange != nullptr ) ) { - sourceBuffers.emplace_back( imf_, "sphericalRange", buffers.sphericalRange, count, true, true ); + sourceBuffers.emplace_back( imf_, "sphericalRange", buffers.sphericalRange, count, true, + true ); } - if ( proto.isDefined( "sphericalAzimuth" ) && buffers.sphericalAzimuth ) + + if ( proto.isDefined( "sphericalAzimuth" ) && ( buffers.sphericalAzimuth != nullptr ) ) { - sourceBuffers.emplace_back( imf_, "sphericalAzimuth", buffers.sphericalAzimuth, count, true, true ); + sourceBuffers.emplace_back( imf_, "sphericalAzimuth", buffers.sphericalAzimuth, count, + true, true ); } - if ( proto.isDefined( "sphericalElevation" ) && buffers.sphericalElevation ) + + if ( proto.isDefined( "sphericalElevation" ) && ( buffers.sphericalElevation != nullptr ) ) { - sourceBuffers.emplace_back( imf_, "sphericalElevation", buffers.sphericalElevation, count, true, true ); + sourceBuffers.emplace_back( imf_, "sphericalElevation", buffers.sphericalElevation, count, + true, true ); } - if ( proto.isDefined( "intensity" ) && buffers.intensity ) + if ( proto.isDefined( "intensity" ) && ( buffers.intensity != nullptr ) ) { sourceBuffers.emplace_back( imf_, "intensity", buffers.intensity, count, true, true ); } - if ( proto.isDefined( "colorRed" ) && buffers.colorRed ) + if ( proto.isDefined( "colorRed" ) && ( buffers.colorRed != nullptr ) ) { sourceBuffers.emplace_back( imf_, "colorRed", buffers.colorRed, count, true ); } - if ( proto.isDefined( "colorGreen" ) && buffers.colorGreen ) + + if ( proto.isDefined( "colorGreen" ) && ( buffers.colorGreen != nullptr ) ) { sourceBuffers.emplace_back( imf_, "colorGreen", buffers.colorGreen, count, true ); } - if ( proto.isDefined( "colorBlue" ) && buffers.colorBlue ) + + if ( proto.isDefined( "colorBlue" ) && ( buffers.colorBlue != nullptr ) ) { sourceBuffers.emplace_back( imf_, "colorBlue", buffers.colorBlue, count, true ); } - if ( proto.isDefined( "returnIndex" ) && buffers.returnIndex ) + if ( proto.isDefined( "returnIndex" ) && ( buffers.returnIndex != nullptr ) ) { sourceBuffers.emplace_back( imf_, "returnIndex", buffers.returnIndex, count, true ); } - if ( proto.isDefined( "returnCount" ) && buffers.returnCount ) + + if ( proto.isDefined( "returnCount" ) && ( buffers.returnCount != nullptr ) ) { sourceBuffers.emplace_back( imf_, "returnCount", buffers.returnCount, count, true ); } - if ( proto.isDefined( "rowIndex" ) && buffers.rowIndex ) + if ( proto.isDefined( "rowIndex" ) && ( buffers.rowIndex != nullptr ) ) { sourceBuffers.emplace_back( imf_, "rowIndex", buffers.rowIndex, count, true ); } - if ( proto.isDefined( "columnIndex" ) && buffers.columnIndex ) + + if ( proto.isDefined( "columnIndex" ) && ( buffers.columnIndex != nullptr ) ) { sourceBuffers.emplace_back( imf_, "columnIndex", buffers.columnIndex, count, true ); } - if ( proto.isDefined( "timeStamp" ) && buffers.timeStamp ) + if ( proto.isDefined( "timeStamp" ) && ( buffers.timeStamp != nullptr ) ) { sourceBuffers.emplace_back( imf_, "timeStamp", buffers.timeStamp, count, true, true ); } - if ( proto.isDefined( "cartesianInvalidState" ) && buffers.cartesianInvalidState ) + if ( proto.isDefined( "cartesianInvalidState" ) && + ( buffers.cartesianInvalidState != nullptr ) ) { - sourceBuffers.emplace_back( imf_, "cartesianInvalidState", buffers.cartesianInvalidState, count, true ); + sourceBuffers.emplace_back( imf_, "cartesianInvalidState", buffers.cartesianInvalidState, + count, true ); } - if ( proto.isDefined( "sphericalInvalidState" ) && buffers.sphericalInvalidState ) + + if ( proto.isDefined( "sphericalInvalidState" ) && + ( buffers.sphericalInvalidState != nullptr ) ) { - sourceBuffers.emplace_back( imf_, "sphericalInvalidState", buffers.sphericalInvalidState, count, true ); + sourceBuffers.emplace_back( imf_, "sphericalInvalidState", buffers.sphericalInvalidState, + count, true ); } - if ( proto.isDefined( "isIntensityInvalid" ) && buffers.isIntensityInvalid ) + + if ( proto.isDefined( "isIntensityInvalid" ) && ( buffers.isIntensityInvalid != nullptr ) ) { - sourceBuffers.emplace_back( imf_, "isIntensityInvalid", buffers.isIntensityInvalid, count, true ); + sourceBuffers.emplace_back( imf_, "isIntensityInvalid", buffers.isIntensityInvalid, count, + true ); } - if ( proto.isDefined( "isColorInvalid" ) && buffers.isColorInvalid ) + + if ( proto.isDefined( "isColorInvalid" ) && ( buffers.isColorInvalid != nullptr ) ) { sourceBuffers.emplace_back( imf_, "isColorInvalid", buffers.isColorInvalid, count, true ); } - if ( proto.isDefined( "isTimeStampInvalid" ) && buffers.isTimeStampInvalid ) + + if ( proto.isDefined( "isTimeStampInvalid" ) && ( buffers.isTimeStampInvalid != nullptr ) ) { - sourceBuffers.emplace_back( imf_, "isTimeStampInvalid", buffers.isTimeStampInvalid, count, true ); + sourceBuffers.emplace_back( imf_, "isTimeStampInvalid", buffers.isTimeStampInvalid, count, + true ); } // E57_EXT_surface_normals - ustring norExtUri; - if ( imf_.extensionsLookupPrefix( "nor", norExtUri ) ) + if ( imf_.extensionsLookupPrefix( "nor" ) ) { - if ( proto.isDefined( "nor:normalX" ) && buffers.normalX ) + if ( proto.isDefined( "nor:normalX" ) && ( buffers.normalX != nullptr ) ) { sourceBuffers.emplace_back( imf_, "nor:normalX", buffers.normalX, count, true, true ); } - if ( proto.isDefined( "nor:normalY" ) && buffers.normalY ) + + if ( proto.isDefined( "nor:normalY" ) && ( buffers.normalY != nullptr ) ) { sourceBuffers.emplace_back( imf_, "nor:normalY", buffers.normalY, count, true, true ); } - if ( proto.isDefined( "nor:normalZ" ) && buffers.normalZ ) + + if ( proto.isDefined( "nor:normalZ" ) && ( buffers.normalZ != nullptr ) ) { sourceBuffers.emplace_back( imf_, "nor:normalZ", buffers.normalZ, count, true, true ); } @@ -1063,39 +1301,43 @@ namespace e57 } // Explicit template instantiation - template CompressedVectorWriter WriterImpl::SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData_t &buffers ); + template CompressedVectorWriter WriterImpl::SetUpData3DPointsData( + int64_t dataIndex, size_t pointCount, const Data3DPointsData_t &buffers ); - template CompressedVectorWriter WriterImpl::SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, - const Data3DPointsData_t &buffers ); + template CompressedVectorWriter WriterImpl::SetUpData3DPointsData( + int64_t dataIndex, size_t pointCount, const Data3DPointsData_t &buffers ); // This function writes out the group data - bool WriterImpl::WriteData3DGroupsData( int64_t dataIndex, int64_t groupCount, int64_t *idElementValue, - int64_t *startPointIndex, int64_t *pointCount ) + bool WriterImpl::WriteData3DGroupsData( int64_t dataIndex, size_t groupCount, + int64_t *idElementValue, int64_t *startPointIndex, + int64_t *pointCount ) { if ( ( dataIndex < 0 ) || ( dataIndex >= data3D_.childCount() ) ) { return false; } - StructureNode scan( data3D_.get( dataIndex ) ); + const StructureNode scan( data3D_.get( dataIndex ) ); if ( !scan.isDefined( "pointGroupingSchemes" ) ) { return false; } - StructureNode pointGroupingSchemes( scan.get( "pointGroupingSchemes" ) ); + + const StructureNode pointGroupingSchemes( scan.get( "pointGroupingSchemes" ) ); if ( !pointGroupingSchemes.isDefined( "groupingByLine" ) ) { return false; } - StructureNode groupingByLine( pointGroupingSchemes.get( "groupingByLine" ) ); + + const StructureNode groupingByLine( pointGroupingSchemes.get( "groupingByLine" ) ); if ( !groupingByLine.isDefined( "groups" ) ) { return false; } + CompressedVectorNode groups( groupingByLine.get( "groups" ) ); std::vector groupSDBuffers; @@ -1110,4 +1352,23 @@ namespace e57 return true; } + StructureNode WriterImpl::GetRawE57Root() + { + return root_; + } + + VectorNode WriterImpl::GetRawData3D() + { + return data3D_; + } + + VectorNode WriterImpl::GetRawImages2D() + { + return images2D_; + } + + ImageFile WriterImpl::GetRawIMF() + { + return imf_; + } } // end namespace e57 diff --git a/src/3rdParty/libE57Format/src/WriterImpl.h b/src/3rdParty/libE57Format/src/WriterImpl.h index b0e7d92ace4aa..d353ddd3f37c1 100644 --- a/src/3rdParty/libE57Format/src/WriterImpl.h +++ b/src/3rdParty/libE57Format/src/WriterImpl.h @@ -1,6 +1,7 @@ /* * Copyright (c) 2010 Stan Coleby (scoleby@intelisum.com) * Copyright (c) 2020 PTC Inc. + * Copyright (c) 2022 Andy Maloney * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by @@ -28,26 +29,31 @@ #pragma once #include "E57SimpleData.h" +#include "E57SimpleWriter.h" namespace e57 { - - //! most of the functions follows Writer class WriterImpl { public: - WriterImpl( const ustring &filePath, const ustring &coordinateMetaData ); - + WriterImpl( const ustring &filePath, const WriterOptions &options ); ~WriterImpl(); + // disallow copying a WriterImpl + WriterImpl( const WriterImpl & ) = delete; + WriterImpl &operator=( WriterImpl const & ) = delete; + WriterImpl( const WriterImpl && ) = delete; + WriterImpl &operator=( const WriterImpl && ) = delete; + bool IsOpen() const; bool Close(); int64_t NewImage2D( Image2D &image2DHeader ); - int64_t WriteImage2DData( int64_t imageIndex, Image2DType imageType, Image2DProjection imageProjection, - void *pBuffer, int64_t start, int64_t count ); + size_t WriteImage2DData( int64_t imageIndex, Image2DType imageType, + Image2DProjection imageProjection, uint8_t *pBuffer, int64_t start, + size_t count ); int64_t NewData3D( Data3D &data3DHeader ); @@ -55,7 +61,7 @@ namespace e57 CompressedVectorWriter SetUpData3DPointsData( int64_t dataIndex, size_t pointCount, const Data3DPointsData_t &buffers ); - bool WriteData3DGroupsData( int64_t dataIndex, int64_t groupCount, int64_t *idElementValue, + bool WriteData3DGroupsData( int64_t dataIndex, size_t groupCount, int64_t *idElementValue, int64_t *startPointIndex, int64_t *pointCount ); StructureNode GetRawE57Root(); @@ -73,15 +79,5 @@ namespace e57 VectorNode data3D_; VectorNode images2D_; - - //! @brief This function writes the projection image - //! @param image 1 of 3 projects or the visual - //! @param imageType identifies the image format desired. - //! @param pBuffer pointer the buffer - //! @param start position in the block to start reading - //! @param count size of desired chuck or buffer size - int64_t WriteImage2DNode( StructureNode image, Image2DType imageType, void *pBuffer, int64_t start, - int64_t count ); }; // end Writer class - } // end namespace e57 diff --git a/src/App/Expression.cpp b/src/App/Expression.cpp index 75ac7e2e37635..bbd5ddd8e05b6 100644 --- a/src/App/Expression.cpp +++ b/src/App/Expression.cpp @@ -62,18 +62,6 @@ using namespace App; FC_LOG_LEVEL_INIT("Expression", true, true) -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif -#ifndef M_E -#define M_E 2.71828182845904523536 -#endif -#ifndef DOUBLE_MAX -# define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ -#endif -#ifndef DOUBLE_MIN -# define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ -#endif #if defined(_MSC_VER) #define strtoll _strtoi64 diff --git a/src/Base/Matrix.cpp b/src/Base/Matrix.cpp index e3e6cd91ea272..67e0e993ca170 100644 --- a/src/Base/Matrix.cpp +++ b/src/Base/Matrix.cpp @@ -373,7 +373,7 @@ bool Matrix4D::toAxisAngle (Vector3d& rclBase, Vector3d& rclDir, double& rfAngle if ( rfAngle > 0.0 ) { - if ( rfAngle < D_PI ) + if ( rfAngle < M_PI ) { rclDir.x = (dMtrx4D[2][1]-dMtrx4D[1][2]); rclDir.y = (dMtrx4D[0][2]-dMtrx4D[2][0]); diff --git a/src/Base/PlacementPyImp.cpp b/src/Base/PlacementPyImp.cpp index 9cf7aaaf9c749..a4dfa2b77236b 100644 --- a/src/Base/PlacementPyImp.cpp +++ b/src/Base/PlacementPyImp.cpp @@ -93,7 +93,7 @@ int PlacementPy::PyInit(PyObject* args, PyObject* /*kwd*/) &(Base::VectorPy::Type), &d, &angle)) { // NOTE: The first parameter defines the translation, the second the rotation axis // and the last parameter defines the rotation angle in degree. - Base::Rotation rot(static_cast(d)->value(), angle/180.0*D_PI); + Base::Rotation rot(static_cast(d)->value(), angle/180.0*M_PI); *getPlacementPtr() = Base::Placement(static_cast(o)->value(),rot); return 0; } diff --git a/src/Base/PreCompiled.h b/src/Base/PreCompiled.h index 2bef608c20550..0a32909d59f7a 100644 --- a/src/Base/PreCompiled.h +++ b/src/Base/PreCompiled.h @@ -25,7 +25,7 @@ #define BASE_PRECOMPILED_H #include - +#include #ifdef _PreComp_ // Python diff --git a/src/Base/Quantity.cpp b/src/Base/Quantity.cpp index 4a1cd384643e8..2d0043ea38d7b 100644 --- a/src/Base/Quantity.cpp +++ b/src/Base/Quantity.cpp @@ -540,7 +540,7 @@ Quantity Quantity::parse(const QString &string) // parse from buffer QuantityParser::YY_BUFFER_STATE my_string_buffer = QuantityParser::yy_scan_string (string.toUtf8().data()); // set the global return variables - QuantResult = Quantity(DOUBLE_MIN); + QuantResult = Quantity(DBL_MIN); // run the parser QuantityParser::yyparse (); // free the scan buffer diff --git a/src/Base/Quantity.h b/src/Base/Quantity.h index 2be7a69998f88..6471b4c4bdea8 100644 --- a/src/Base/Quantity.h +++ b/src/Base/Quantity.h @@ -27,14 +27,6 @@ #include "Unit.h" #include -// NOLINTBEGIN -#ifndef DOUBLE_MAX -# define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ -#endif -#ifndef DOUBLE_MIN -# define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ -#endif -// NOLINTEND namespace Base { class UnitsSchema; diff --git a/src/Base/QuantityParser.c b/src/Base/QuantityParser.c index 02d15502abeec..8bf3927bca0ea 100644 --- a/src/Base/QuantityParser.c +++ b/src/Base/QuantityParser.c @@ -67,12 +67,6 @@ #define YYSTYPE Quantity #define yyparse Quantity_yyparse #define yyerror Quantity_yyerror - #ifndef DOUBLE_MAX - # define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ - #endif - #ifndef DOUBLE_MIN - # define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ - #endif #line 79 "QuantityParser.c" /* yacc.c:339 */ @@ -1300,7 +1294,7 @@ yyparse (void) { case 2: #line 34 "QuantityParser.y" /* yacc.c:1646 */ - { QuantResult = Quantity(DOUBLE_MIN); /* empty input */ } + { QuantResult = Quantity(DBL_MIN); /* empty input */ } #line 1305 "QuantityParser.c" /* yacc.c:1646 */ break; diff --git a/src/Base/QuantityParser.y b/src/Base/QuantityParser.y index 906b9cab6fec2..79d90a336122e 100644 --- a/src/Base/QuantityParser.y +++ b/src/Base/QuantityParser.y @@ -25,12 +25,6 @@ #define YYSTYPE Quantity #define yyparse Quantity_yyparse #define yyerror Quantity_yyerror - #ifndef DOUBLE_MAX - # define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ - #endif - #ifndef DOUBLE_MIN - # define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ - #endif %} @@ -49,7 +43,7 @@ %% - input: { QuantResult = Quantity(DOUBLE_MIN); /* empty input */ } + input: { QuantResult = Quantity(DBL_MIN); /* empty input */ } | num { QuantResult = $1 ; } | unit { QuantResult = $1 ; } | quantity { QuantResult = $1 ; } diff --git a/src/Base/QuantityPyImp.cpp b/src/Base/QuantityPyImp.cpp index 01a12b14ef0f9..7fc9fcdead88b 100644 --- a/src/Base/QuantityPyImp.cpp +++ b/src/Base/QuantityPyImp.cpp @@ -26,7 +26,7 @@ #include "QuantityPy.h" #include "UnitPy.h" #include "QuantityPy.cpp" - +#include using namespace Base; @@ -85,7 +85,7 @@ int QuantityPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); // set by PyArg_ParseTuple() - double f = DOUBLE_MAX; + double f = DBL_MAX; if (PyArg_ParseTuple(args,"dO!",&f,&(Base::UnitPy::Type), &object)) { *self = Quantity(f,*(static_cast(object)->getUnitPtr())); return 0; @@ -107,7 +107,7 @@ int QuantityPy::PyInit(PyObject* args, PyObject* /*kwd*/) int i8=0; PyErr_Clear(); // set by PyArg_ParseTuple() if (PyArg_ParseTuple(args, "|diiiiiiii", &f,&i1,&i2,&i3,&i4,&i5,&i6,&i7,&i8)) { - if (f < DOUBLE_MAX) { + if (f < DBL_MAX) { *self = Quantity(f,Unit{static_cast(i1), static_cast(i2), static_cast(i3), @@ -203,7 +203,7 @@ PyObject* QuantityPy::getValueAs(PyObject *args) } if (!quant.isValid()) { - double f = DOUBLE_MAX; + double f = DBL_MAX; int i1=0; int i2=0; int i3=0; @@ -214,7 +214,7 @@ PyObject* QuantityPy::getValueAs(PyObject *args) int i8=0; PyErr_Clear(); if (PyArg_ParseTuple(args, "d|iiiiiiii", &f,&i1,&i2,&i3,&i4,&i5,&i6,&i7,&i8)) { - if (f < DOUBLE_MAX) { + if (f < DBL_MAX) { quant = Quantity(f,Unit{static_cast(i1), static_cast(i2), static_cast(i3), diff --git a/src/Base/Rotation.cpp b/src/Base/Rotation.cpp index 204885147df27..a4e348ab48f94 100644 --- a/src/Base/Rotation.cpp +++ b/src/Base/Rotation.cpp @@ -280,7 +280,7 @@ void Rotation::setValue(const Vector3d & axis, const double fAngle) // // normalization of the angle to be in [0, 2pi[ _angle = fAngle; - double theAngle = fAngle - floor(fAngle / (2.0 * D_PI))*(2.0 * D_PI); + double theAngle = fAngle - floor(fAngle / (2.0 * M_PI))*(2.0 * M_PI); this->quat[3] = cos(theAngle/2.0); Vector3d norm = axis; @@ -689,9 +689,9 @@ void Rotation::setYawPitchRoll(double y, double p, double r) { // The Euler angles (yaw,pitch,roll) are in XY'Z''-notation // convert to radians - y = (y/180.0)*D_PI; - p = (p/180.0)*D_PI; - r = (r/180.0)*D_PI; + y = (y/180.0)*M_PI; + p = (p/180.0)*M_PI; + r = (r/180.0)*M_PI; double c1 = cos(y/2.0); double s1 = sin(y/2.0); @@ -726,25 +726,25 @@ void Rotation::getYawPitchRoll(double& y, double& p, double& r) const if (fabs(qd2-1.0) <= 16 * DBL_EPSILON) { // Tolerance copied from OCC "gp_Quaternion.cxx" // north pole y = 0.0; - p = D_PI/2.0; + p = M_PI/2.0; r = 2.0 * atan2(quat[0],quat[3]); } else if (fabs(qd2+1.0) <= 16 * DBL_EPSILON) { // Tolerance copied from OCC "gp_Quaternion.cxx" // south pole y = 0.0; - p = -D_PI/2.0; + p = -M_PI/2.0; r = 2.0 * atan2(quat[0],quat[3]); } else { y = atan2(2.0*(q01+q23),(q00+q33)-(q11+q22)); - p = qd2 > 1.0 ? D_PI/2.0 : (qd2 < -1.0 ? -D_PI/2.0 : asin (qd2)); + p = qd2 > 1.0 ? M_PI/2.0 : (qd2 < -1.0 ? -M_PI/2.0 : asin (qd2)); r = atan2(2.0*(q12+q03),(q22+q33)-(q00+q11)); } // convert to degree - y = (y/D_PI)*180; - p = (p/D_PI)*180; - r = (r/D_PI)*180; + y = (y/M_PI)*180; + p = (p/M_PI)*180; + r = (r/M_PI)*180; } bool Rotation::isSame(const Rotation& q) const @@ -959,9 +959,9 @@ void Rotation::setEulerAngles(EulerSequence theOrder, EulerSequence_Parameters o = translateEulerSequence (theOrder); - theAlpha *= D_PI/180.0; - theBeta *= D_PI/180.0; - theGamma *= D_PI/180.0; + theAlpha *= M_PI/180.0; + theBeta *= M_PI/180.0; + theGamma *= M_PI/180.0; double a = theAlpha, b = theBeta, c = theGamma; if ( ! o.isExtrinsic ) @@ -1060,7 +1060,7 @@ void Rotation::getEulerAngles(EulerSequence theOrder, theGamma = aFirst; } - theAlpha *= 180.0/D_PI; - theBeta *= 180.0/D_PI; - theGamma *= 180.0/D_PI; + theAlpha *= 180.0/M_PI; + theBeta *= 180.0/M_PI; + theGamma *= 180.0/M_PI; } diff --git a/src/Base/Tools2D.cpp b/src/Base/Tools2D.cpp index 6b61f526cee00..401d011307706 100644 --- a/src/Base/Tools2D.cpp +++ b/src/Base/Tools2D.cpp @@ -43,7 +43,7 @@ double Vector2d::GetAngle (const Vector2d &rclVect) const { fNum = (*this * rclVect) / fDivid; if (fNum < -1) - return D_PI; + return M_PI; else if (fNum > 1) return 0.0; @@ -51,7 +51,7 @@ double Vector2d::GetAngle (const Vector2d &rclVect) const return acos(fNum); } else - return -FLOAT_MAX; // division by zero + return -FLT_MAX; // division by zero } void Vector2d::ProjectToLine (const Vector2d &rclPt, const Vector2d &rclLine) @@ -175,11 +175,11 @@ bool Line2d::Intersect (const Line2d& rclLine, Vector2d &rclV) const if (fabs (clV2.x - clV1.x) > 1e-10) m1 = (clV2.y - clV1.y) / (clV2.x - clV1.x); else - m1 = DOUBLE_MAX; + m1 = DBL_MAX; if (fabs (rclLine.clV2.x - rclLine.clV1.x) > 1e-10) m2 = (rclLine.clV2.y - rclLine.clV1.y) / (rclLine.clV2.x - rclLine.clV1.x); else - m2 = DOUBLE_MAX; + m2 = DBL_MAX; if (m1 == m2) /****** RETURN ERR (parallel lines) *************/ return false; @@ -187,13 +187,13 @@ bool Line2d::Intersect (const Line2d& rclLine, Vector2d &rclV) const b2 = rclLine.clV1.y - m2 * rclLine.clV1.x; // calc intersection - if (m1 == DOUBLE_MAX) + if (m1 == DBL_MAX) { rclV.x = clV1.x; rclV.y = m2 * rclV.x + b2; } else - if (m2 == DOUBLE_MAX) + if (m2 == DBL_MAX) { rclV.x = rclLine.clV1.x; rclV.y = m1 * rclV.x + b1; diff --git a/src/Base/Tools2D.h b/src/Base/Tools2D.h index d2a2b39098759..7b289ad4651b0 100644 --- a/src/Base/Tools2D.h +++ b/src/Base/Tools2D.h @@ -456,8 +456,8 @@ inline bool Line2d::Contains (const Vector2d &rclV) const inline BoundBox2d::BoundBox2d () { - MinX = MinY = DOUBLE_MAX; - MaxX = MaxY = - DOUBLE_MAX; + MinX = MinY = DBL_MAX; + MaxX = MaxY = DBL_MIN; } inline BoundBox2d::BoundBox2d (double fX1, double fY1, double fX2, double fY2) @@ -516,8 +516,8 @@ inline Vector2d BoundBox2d::GetCenter() const inline void BoundBox2d::SetVoid() { - MinX = MinY = DOUBLE_MAX; - MaxX = MaxY = -DOUBLE_MAX; + MinX = MinY = DBL_MAX; + MaxX = MaxY = DBL_MIN; } inline void BoundBox2d::Add(const Vector2d &v) diff --git a/src/Base/UnitsApi.cpp b/src/Base/UnitsApi.cpp index cfabc98db3c74..8e7a0f313d5f3 100644 --- a/src/Base/UnitsApi.cpp +++ b/src/Base/UnitsApi.cpp @@ -39,18 +39,6 @@ #include "UnitsSchemaMmMin.h" #include "UnitsSchemaFemMilliMeterNewton.h" -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif -#ifndef M_E -#define M_E 2.71828182845904523536 -#endif -#ifndef DOUBLE_MAX -# define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ -#endif -#ifndef DOUBLE_MIN -# define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ -#endif using namespace Base; diff --git a/src/Base/Vector3D.h b/src/Base/Vector3D.h index e2f37a6f64a18..2ed72ef02c93f 100644 --- a/src/Base/Vector3D.h +++ b/src/Base/Vector3D.h @@ -28,29 +28,6 @@ #include #include -#ifndef F_PI -# define F_PI 3.1415926f -#endif - -#ifndef D_PI -# define D_PI 3.141592653589793 -#endif - -#ifndef FLOAT_MAX -# define FLOAT_MAX 3.402823466E+38F -#endif - -#ifndef FLOAT_MIN -# define FLOAT_MIN 1.175494351E-38F -#endif - -#ifndef DOUBLE_MAX -# define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ -#endif - -#ifndef DOUBLE_MIN -# define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ -#endif namespace Base { @@ -60,7 +37,7 @@ struct float_traits { }; template <> struct float_traits { using float_type = float; - static inline float_type pi() { return F_PI; } + static inline float_type pi() { return M_PI; } static inline float_type epsilon() { return FLT_EPSILON; } static inline float_type maximum() { return FLT_MAX; } }; @@ -68,7 +45,7 @@ struct float_traits { template <> struct float_traits { using float_type = double; - static inline float_type pi() { return D_PI; } + static inline float_type pi() { return M_PI; } static inline float_type epsilon() { return DBL_EPSILON; } static inline float_type maximum() { return DBL_MAX; } }; diff --git a/src/Gui/InputField.cpp b/src/Gui/InputField.cpp index ae2641cb45f7d..b8b5b9dc028b4 100644 --- a/src/Gui/InputField.cpp +++ b/src/Gui/InputField.cpp @@ -72,8 +72,8 @@ InputField::InputField(QWidget * parent) ExpressionWidget(), validInput(true), actUnitValue(0), - Maximum(DOUBLE_MAX), - Minimum(-DOUBLE_MAX), + Maximum(DBL_MAX), + Minimum(DBL_MIN), StepSize(1.0), HistorySize(5), SaveSize(5) diff --git a/src/Gui/QuantitySpinBox.cpp b/src/Gui/QuantitySpinBox.cpp index 91bc452d6a6b9..ebc6a5b035f12 100644 --- a/src/Gui/QuantitySpinBox.cpp +++ b/src/Gui/QuantitySpinBox.cpp @@ -66,8 +66,8 @@ class QuantitySpinBoxPrivate pendingEmit(false), checkRangeInExpression(false), unitValue(0), - maximum(DOUBLE_MAX), - minimum(-DOUBLE_MAX), + maximum(DBL_MAX), + minimum(DBL_MIN), singleStep(1.0), q_ptr(q) { diff --git a/src/Gui/Transform.cpp b/src/Gui/Transform.cpp index be98701d83c41..b03a898a58fa6 100644 --- a/src/Gui/Transform.cpp +++ b/src/Gui/Transform.cpp @@ -396,7 +396,7 @@ Base::Placement Transform::getPlacementData() const if (index == 0) { Base::Vector3d dir = getDirection(); - rot.setValue(Base::Vector3d(dir.x,dir.y,dir.z),ui->angle->value().getValue()*D_PI/180.0); + rot.setValue(Base::Vector3d(dir.x,dir.y,dir.z),ui->angle->value().getValue()*M_PI/180.0); } else if (index == 1) { rot.setYawPitchRoll( diff --git a/src/Mod/Drawing/App/DrawingExport.cpp b/src/Mod/Drawing/App/DrawingExport.cpp index 67341c6610496..e5c1bfcdf657b 100644 --- a/src/Mod/Drawing/App/DrawingExport.cpp +++ b/src/Mod/Drawing/App/DrawingExport.cpp @@ -217,7 +217,7 @@ void SVGOutput::printCircle(const BRepAdaptor_Curve& c, std::ostream& out) else { // See also https://developer.mozilla.org/en/SVG/Tutorial/Paths char xar = '0'; // x-axis-rotation - char las = (l - f > D_PI) ? '1' : '0';// large-arc-flag + char las = (l - f > M_PI) ? '1' : '0';// large-arc-flag char swp = (a < 0) ? '1' : '0';// sweep-flag, i.e. clockwise (0) or counter-clockwise (1) out << ""; @@ -263,7 +263,7 @@ void SVGOutput::printEllipse(const BRepAdaptor_Curve& c, int id, std::ostream& o } // arc of ellipse else { - char las = (l - f > D_PI) ? '1' : '0';// large-arc-flag + char las = (l - f > M_PI) ? '1' : '0';// large-arc-flag char swp = (a < 0) ? '1' : '0';// sweep-flag, i.e. clockwise (0) or counter-clockwise (1) out << "" << std::endl; @@ -511,21 +511,14 @@ void DXFOutput::printCircle(const BRepAdaptor_Curve& c, std::ostream& out) // arc of circle else { - // See also https://developer.mozilla.org/en/SVG/Tutorial/Paths - /*char xar = '0'; // x-axis-rotation - char las = (l-f > D_PI) ? '1' : '0'; // large-arc-flag - char swp = (a < 0) ? '1' : '0'; // sweep-flag, i.e. clockwise (0) or counter-clockwise (1) - out << "";*/ + double ax = s.X() - p.X(); double ay = s.Y() - p.Y(); double bx = e.X() - p.X(); double by = e.Y() - p.Y(); - double start_angle = atan2(ay, ax) * 180 / D_PI; - double end_angle = atan2(by, bx) * 180 / D_PI; + double start_angle = atan2(ay, ax) * 180 / M_PI; + double end_angle = atan2(by, bx) * 180 / M_PI; if (a > 0) { @@ -566,27 +559,8 @@ void DXFOutput::printEllipse(const BRepAdaptor_Curve& c, int /*id*/, std::ostrea double r2 = ellp.MinorRadius(); double dp = ellp.Axis().Direction().Dot(gp_Vec(0, 0, 1)); - // a full ellipse - /* if (s.SquareDistance(e) < 0.001) { - out << ""; - } - // arc of ellipse - else { - // See also https://developer.mozilla.org/en/SVG/Tutorial/Paths - gp_Dir xaxis = ellp.XAxis().Direction(); - Standard_Real angle = xaxis.Angle(gp_Dir(1,0,0)); - angle = Base::toDegrees(angle); - char las = (l-f > D_PI) ? '1' : '0'; // large-arc-flag - char swp = (a < 0) ? '1' : '0'; // sweep-flag, i.e. clockwise (0) or counter-clockwise (1) - out << ""; - }*/ gp_Dir xaxis = ellp.XAxis().Direction(); double angle = xaxis.AngleWithRef(gp_Dir(1, 0, 0), gp_Dir(0, 0, -1)); - // double rotation = Base::toDegrees(angle); double start_angle = c.FirstParameter(); double end_angle = c.LastParameter(); @@ -653,10 +627,6 @@ void DXFOutput::printBSpline(const BRepAdaptor_Curve& c, return; } - // GeomConvert_BSplineCurveToBezierCurve crt(spline); - // GeomConvert_BSplineCurveKnotSplitting crt(spline,0); - // Standard_Integer arcs = crt.NbArcs(); - // Standard_Integer arcs = crt.NbSplits()-1; Standard_Integer m = 0; if (spline->IsPeriodic()) { m = spline->NbPoles() + 2 * spline->Degree() - spline->Multiplicity(1) + 2; diff --git a/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp index 4db1e0d7275c7..8178daecad152 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp @@ -43,8 +43,8 @@ DlgSettingsFemCcxImp::DlgSettingsFemCcxImp(QWidget* parent) { ui->setupUi(this); // set ranges - ui->dsb_ccx_analysis_time->setMaximum(FLOAT_MAX); - ui->dsb_ccx_initial_time_step->setMaximum(FLOAT_MAX); + ui->dsb_ccx_analysis_time->setMaximum(FLT_MAX); + ui->dsb_ccx_initial_time_step->setMaximum(FLT_MAX); // determine number of CPU cores int processor_count = QThread::idealThreadCount(); ui->sb_ccx_numcpu->setMaximum(processor_count); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp b/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp index 114f2e8c5d596..766689be9b989 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp @@ -65,18 +65,18 @@ TaskFemConstraintBearing::TaskFemConstraintBearing(ViewProviderFemConstraint* Co this->groupLayout()->addWidget(proxy); // setup ranges - ui->spinDiameter->setMinimum(-FLOAT_MAX); - ui->spinDiameter->setMaximum(FLOAT_MAX); - ui->spinOtherDiameter->setMinimum(-FLOAT_MAX); - ui->spinOtherDiameter->setMaximum(FLOAT_MAX); - ui->spinCenterDistance->setMinimum(-FLOAT_MAX); - ui->spinCenterDistance->setMaximum(FLOAT_MAX); - ui->spinForce->setMinimum(-FLOAT_MAX); - ui->spinForce->setMaximum(FLOAT_MAX); - ui->spinTensionForce->setMinimum(-FLOAT_MAX); - ui->spinTensionForce->setMaximum(FLOAT_MAX); - ui->spinDistance->setMinimum(-FLOAT_MAX); - ui->spinDistance->setMaximum(FLOAT_MAX); + ui->spinDiameter->setMinimum(FLT_MIN); + ui->spinDiameter->setMaximum(FLT_MAX); + ui->spinOtherDiameter->setMinimum(FLT_MIN); + ui->spinOtherDiameter->setMaximum(FLT_MAX); + ui->spinCenterDistance->setMinimum(FLT_MIN); + ui->spinCenterDistance->setMaximum(FLT_MAX); + ui->spinForce->setMinimum(FLT_MIN); + ui->spinForce->setMaximum(FLT_MAX); + ui->spinTensionForce->setMinimum(FLT_MIN); + ui->spinTensionForce->setMaximum(FLT_MAX); + ui->spinDistance->setMinimum(FLT_MIN); + ui->spinDistance->setMaximum(FLT_MAX); // Get the feature data Fem::ConstraintBearing* pcConstraint = diff --git a/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp b/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp index eb636db99f83a..ae5ab0e0da53c 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp @@ -66,18 +66,18 @@ TaskFemConstraintDisplacement::TaskFemConstraintDisplacement( this->groupLayout()->addWidget(proxy); // setup ranges - ui->spinxDisplacement->setMinimum(-FLOAT_MAX); - ui->spinxDisplacement->setMaximum(FLOAT_MAX); - ui->spinyDisplacement->setMinimum(-FLOAT_MAX); - ui->spinyDisplacement->setMaximum(FLOAT_MAX); - ui->spinzDisplacement->setMinimum(-FLOAT_MAX); - ui->spinzDisplacement->setMaximum(FLOAT_MAX); - ui->spinxRotation->setMinimum(-FLOAT_MAX); - ui->spinxRotation->setMaximum(FLOAT_MAX); - ui->spinyRotation->setMinimum(-FLOAT_MAX); - ui->spinyRotation->setMaximum(FLOAT_MAX); - ui->spinzRotation->setMinimum(-FLOAT_MAX); - ui->spinzRotation->setMaximum(FLOAT_MAX); + ui->spinxDisplacement->setMinimum(FLT_MIN); + ui->spinxDisplacement->setMaximum(FLT_MAX); + ui->spinyDisplacement->setMinimum(FLT_MIN); + ui->spinyDisplacement->setMaximum(FLT_MAX); + ui->spinzDisplacement->setMinimum(FLT_MIN); + ui->spinzDisplacement->setMaximum(FLT_MAX); + ui->spinxRotation->setMinimum(FLT_MIN); + ui->spinxRotation->setMaximum(FLT_MAX); + ui->spinyRotation->setMinimum(FLT_MIN); + ui->spinyRotation->setMaximum(FLT_MAX); + ui->spinzRotation->setMinimum(FLT_MIN); + ui->spinzRotation->setMaximum(FLT_MAX); // Get the feature data Fem::ConstraintDisplacement* pcConstraint = diff --git a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp index fe8b0c1703c1a..2f5da2b61c137 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp @@ -139,18 +139,18 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( this, &TaskFemConstraintFluidBoundary::onReferenceDeleted); // setup ranges - ui->spinBoundaryValue->setMinimum(-FLOAT_MAX); - ui->spinBoundaryValue->setMaximum(FLOAT_MAX); + ui->spinBoundaryValue->setMinimum(FLT_MIN); + ui->spinBoundaryValue->setMaximum(FLT_MAX); ui->spinTurbulentIntensityValue->setMinimum(0.0); - ui->spinTurbulentIntensityValue->setMaximum(FLOAT_MAX); + ui->spinTurbulentIntensityValue->setMaximum(FLT_MAX); ui->spinTurbulentLengthValue->setMinimum(0.0); - ui->spinTurbulentLengthValue->setMaximum(FLOAT_MAX); + ui->spinTurbulentLengthValue->setMaximum(FLT_MAX); ui->spinTemperatureValue->setMinimum(-273.15); - ui->spinTemperatureValue->setMaximum(FLOAT_MAX); + ui->spinTemperatureValue->setMaximum(FLT_MAX); ui->spinHeatFluxValue->setMinimum(0.0); - ui->spinHeatFluxValue->setMaximum(FLOAT_MAX); + ui->spinHeatFluxValue->setMaximum(FLT_MAX); ui->spinHTCoeffValue->setMinimum(0.0); - ui->spinHTCoeffValue->setMaximum(FLOAT_MAX); + ui->spinHTCoeffValue->setMaximum(FLT_MAX); connect(ui->comboBoundaryType, qOverload(&QComboBox::currentIndexChanged), this, &TaskFemConstraintFluidBoundary::onBoundaryTypeChanged); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp b/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp index d8c309723139d..5a2ea20076ca1 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp @@ -92,7 +92,7 @@ TaskFemConstraintForce::TaskFemConstraintForce(ViewProviderFemConstraintForce* C // Fill data into dialog elements ui->spinForce->setMinimum(0); - ui->spinForce->setMaximum(FLOAT_MAX); + ui->spinForce->setMaximum(FLT_MAX); ui->spinForce->setValue(f); ui->listReferences->clear(); for (std::size_t i = 0; i < Objects.size(); i++) diff --git a/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp b/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp index b9c1c23554744..27701dd6ebc19 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp @@ -78,10 +78,10 @@ TaskFemConstraintGear::TaskFemConstraintGear(ViewProviderFemConstraint *Constrai // Fill data into dialog elements ui->spinDiameter->setMinimum(0); - ui->spinDiameter->setMaximum(FLOAT_MAX); + ui->spinDiameter->setMaximum(FLT_MAX); ui->spinDiameter->setValue(dia); ui->spinForce->setMinimum(0); - ui->spinForce->setMaximum(FLOAT_MAX); + ui->spinForce->setMaximum(FLT_MAX); ui->spinForce->setValue(force); ui->spinForceAngle->setMinimum(-360); ui->spinForceAngle->setMaximum(360); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp b/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp index 9f05ca7f6444b..c2eeaab41b75d 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp @@ -90,10 +90,10 @@ TaskFemConstraintHeatflux::TaskFemConstraintHeatflux( // Fill data into dialog elements ui->if_ambienttemp->setMinimum(0); - ui->if_ambienttemp->setMaximum(FLOAT_MAX); + ui->if_ambienttemp->setMaximum(FLT_MAX); ui->if_filmcoef->setMinimum(0); - ui->if_filmcoef->setMaximum(FLOAT_MAX); + ui->if_filmcoef->setMaximum(FLT_MAX); std::string constraint_type = pcConstraint->ConstraintType.getValueAsString(); if (constraint_type == "Convection") { diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp b/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp index c17312ae447ec..c075dc25435f1 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp @@ -75,7 +75,7 @@ TaskFemConstraintPressure::TaskFemConstraintPressure( // Fill data into dialog elements ui->if_pressure->setMinimum(0); - ui->if_pressure->setMaximum(FLOAT_MAX); + ui->if_pressure->setMaximum(FLT_MAX); Base::Quantity p = Base::Quantity(1000 * (pcConstraint->Pressure.getValue()), Base::Unit::Stress); ui->if_pressure->setValue(p); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp b/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp index ec0d9b6d8d9ef..61b679b9e2d5b 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp @@ -67,15 +67,15 @@ TaskFemConstraintPulley::TaskFemConstraintPulley(ViewProviderFemConstraintPulley // Fill data into dialog elements ui->spinOtherDiameter->setMinimum(0); - ui->spinOtherDiameter->setMaximum(FLOAT_MAX); + ui->spinOtherDiameter->setMaximum(FLT_MAX); ui->spinOtherDiameter->setValue(otherdia); ui->spinCenterDistance->setMinimum(0); - ui->spinCenterDistance->setMaximum(FLOAT_MAX); + ui->spinCenterDistance->setMaximum(FLT_MAX); ui->spinCenterDistance->setValue(centerdist); ui->checkIsDriven->setChecked(isdriven); - ui->spinForce->setMinimum(-FLOAT_MAX); + ui->spinForce->setMinimum(FLT_MIN); ui->spinTensionForce->setMinimum(0); - ui->spinTensionForce->setMaximum(FLOAT_MAX); + ui->spinTensionForce->setMaximum(FLT_MAX); ui->spinTensionForce->setValue(tensionforce); // Adjust ui diff --git a/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp b/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp index c3e4264db28ed..9e81cc9ee1630 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp @@ -75,7 +75,7 @@ TaskFemConstraintSpring::TaskFemConstraintSpring(ViewProviderFemConstraintSpring ui->if_norm->setUnit(pcConstraint->NormalStiffness.getUnit()); ui->if_norm->setMinimum( 0);// TODO fix this ------------------------------------------------------------------- - ui->if_norm->setMaximum(FLOAT_MAX); + ui->if_norm->setMaximum(FLT_MAX); Base::Quantity ns = Base::Quantity((pcConstraint->NormalStiffness.getValue()), Base::Unit::Stiffness); ui->if_norm->setValue(ns); @@ -83,7 +83,7 @@ TaskFemConstraintSpring::TaskFemConstraintSpring(ViewProviderFemConstraintSpring ui->if_tan->setUnit(pcConstraint->TangentialStiffness.getUnit()); ui->if_tan->setMinimum( 0);// TODO fix this ------------------------------------------------------------------- - ui->if_tan->setMaximum(FLOAT_MAX); + ui->if_tan->setMaximum(FLT_MAX); Base::Quantity ts = Base::Quantity((pcConstraint->TangentialStiffness.getValue()), Base::Unit::Stiffness); ui->if_tan->setValue(ts); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp b/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp index cd876204549b3..1c0500f5efecc 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp @@ -66,7 +66,7 @@ TaskFemConstraintTemperature::TaskFemConstraintTemperature( // Fill data into dialog elements ui->if_temperature->setMinimum(0); - ui->if_temperature->setMaximum(FLOAT_MAX); + ui->if_temperature->setMaximum(FLT_MAX); std::string constraint_type = pcConstraint->ConstraintType.getValueAsString(); if (constraint_type == "Temperature") { diff --git a/src/Mod/Mesh/App/Core/Algorithm.cpp b/src/Mod/Mesh/App/Core/Algorithm.cpp index 149f218f68127..0db710e7ffaea 100644 --- a/src/Mod/Mesh/App/Core/Algorithm.cpp +++ b/src/Mod/Mesh/App/Core/Algorithm.cpp @@ -272,7 +272,7 @@ float MeshAlgorithm::GetAverageEdgeLength() const float MeshAlgorithm::GetMinimumEdgeLength() const { - float fLen = FLOAT_MAX; + float fLen = FLT_MAX; MeshFacetIterator cF(_rclMesh); for (cF.Init(); cF.More(); cF.Next()) { for (int i=0; i<3; i++) @@ -1356,7 +1356,7 @@ bool MeshAlgorithm::NearestPointFromPoint (const Base::Vector3f &rclPt, FacetInd return false; // calc each facet - float fMinDist = FLOAT_MAX; + float fMinDist = FLT_MAX; FacetIndex ulInd = FACET_INDEX_MAX; MeshFacetIterator pF(_rclMesh); for (pF.Init(); pF.More(); pF.Next()) diff --git a/src/Mod/Mesh/App/Core/Approximation.cpp b/src/Mod/Mesh/App/Core/Approximation.cpp index e1b73e66e1d6b..c5cfd18e26ae5 100644 --- a/src/Mod/Mesh/App/Core/Approximation.cpp +++ b/src/Mod/Mesh/App/Core/Approximation.cpp @@ -143,7 +143,7 @@ float PlaneFit::Fit() { _bIsFitted = true; if (CountPoints() < 3) - return FLOAT_MAX; + return FLT_MAX; double sxx,sxy,sxz,syy,syz,szz,mx,my,mz; sxx=sxy=sxz=syy=syz=szz=mx=my=mz=0.0; @@ -191,7 +191,7 @@ float PlaneFit::Fit() akMat.EigenDecomposition(rkRot, rkDiag); } catch (const std::exception&) { - return FLOAT_MAX; + return FLT_MAX; } // We know the Eigenvalues are ordered @@ -199,7 +199,7 @@ float PlaneFit::Fit() // // points describe a line or even are identical if (rkDiag(1,1) <= 0) - return FLOAT_MAX; + return FLT_MAX; Wm4::Vector3 U = rkRot.GetColumn(1); Wm4::Vector3 V = rkRot.GetColumn(2); @@ -208,7 +208,7 @@ float PlaneFit::Fit() // It may happen that the result have nan values for (int i=0; i<3; i++) { if (boost::math::isnan(W[i])) - return FLOAT_MAX; + return FLT_MAX; } // In some cases when the points exactly lie on a plane it can happen that @@ -236,7 +236,7 @@ float PlaneFit::Fit() // In case sigma is nan if (boost::math::isnan(sigma)) - return FLOAT_MAX; + return FLT_MAX; // This must be caused by some round-off errors. Theoretically it's impossible // that 'sigma' becomes negative because the covariance matrix is positive semi-definite. @@ -293,7 +293,7 @@ Base::Vector3f PlaneFit::GetNormal() const float PlaneFit::GetDistanceToPlane(const Base::Vector3f &rcPoint) const { - float fResult = FLOAT_MAX; + float fResult = FLT_MAX; if (_bIsFitted) fResult = (rcPoint - _vBase) * _vDirW; return fResult; @@ -306,7 +306,7 @@ float PlaneFit::GetStdDeviation() const // Standard deviation: SD=SQRT(VAR) // Standard error of the mean: SE=SD/SQRT(N) if (!_bIsFitted) - return FLOAT_MAX; + return FLT_MAX; float fSumXi = 0.0f, fSumXi2 = 0.0f, fMean = 0.0f, fDist = 0.0f; @@ -330,11 +330,11 @@ float PlaneFit::GetSignedStdDeviation() const // of normal direction the value will be // positive otherwise negative if (!_bIsFitted) - return FLOAT_MAX; + return FLT_MAX; float fSumXi = 0.0f, fSumXi2 = 0.0f, fMean = 0.0f, fDist = 0.0f; - float fMinDist = FLOAT_MAX; + float fMinDist = FLT_MAX; float fFactor; float ulPtCt = float(CountPoints()); @@ -397,7 +397,7 @@ void PlaneFit::Dimension(float& length, float& width) const std::vector PlaneFit::GetLocalPoints() const { std::vector localPoints; - if (_bIsFitted && _fLastResult < FLOAT_MAX) { + if (_bIsFitted && _fLastResult < FLT_MAX) { Base::Vector3d bs = Base::convertTo(this->_vBase); Base::Vector3d ex = Base::convertTo(this->_vDirU); Base::Vector3d ey = Base::convertTo(this->_vDirV); @@ -469,12 +469,12 @@ double QuadraticFit::GetCoeff(std::size_t ulIndex) const if( _bIsFitted ) return _fCoeff[ ulIndex ]; else - return double(FLOAT_MAX); + return double(FLT_MAX); } float QuadraticFit::Fit() { - float fResult = FLOAT_MAX; + float fResult = FLT_MAX; if (CountPoints() > 0) { std::vector< Wm4::Vector3 > cPts; @@ -493,27 +493,6 @@ void QuadraticFit::CalcEigenValues(double &dLambda1, double &dLambda2, double &d { assert( _bIsFitted ); - /* - * F(x,y,z) = a11*x*x + a22*y*y + a33*z*z +2*a12*x*y + 2*a13*x*z + 2*a23*y*z + 2*a10*x + 2*a20*y + 2*a30*z * a00 = 0 - * - * Form matrix: - * - * ( a11 a12 a13 ) - * A = ( a21 a22 a23 ) where a[i,j] = a[j,i] - * ( a31 a32 a33 ) - * - * Coefficients of the Quadrik-Fit based on the notation used here: - * - * 0 = C[0] + C[1]*X + C[2]*Y + C[3]*Z + C[4]*X^2 + C[5]*Y^2 - * + C[6]*Z^2 + C[7]*X*Y + C[8]*X*Z + C[9]*Y*Z - * - * Square: a11 := c[4], a22 := c[5], a33 := c[6] - * Mixed: a12 := c[7]/2, a13 := c[8]/2, a23 := c[9]/2 - * Linear: a10 := c[1]/2, a20 := c[2]/2, a30 := c[3]/2 - * Constant: a00 := c[0] - * - */ - Wm4::Matrix3 akMat(_fCoeff[4], _fCoeff[7]/2.0, _fCoeff[8]/2.0, _fCoeff[7]/2.0, _fCoeff[5], _fCoeff[9]/2.0, _fCoeff[8]/2.0, _fCoeff[9]/2.0, _fCoeff[6] ); @@ -544,14 +523,14 @@ void QuadraticFit::CalcZValues( double x, double y, double &dZ1, double &dZ2 ) c 4*_fCoeff[6]*_fCoeff[7]*x*y-4*_fCoeff[6]*_fCoeff[4]*x*x-4*_fCoeff[6]*_fCoeff[5]*y*y; if (fabs( _fCoeff[6] ) < 0.000005) { - dZ1 = double(FLOAT_MAX); - dZ2 = double(FLOAT_MAX); + dZ1 = double(FLT_MAX); + dZ2 = double(FLT_MAX); return; } if (dDisk < 0.0) { - dZ1 = double(FLOAT_MAX); - dZ2 = double(FLOAT_MAX); + dZ1 = double(FLT_MAX); + dZ2 = double(FLT_MAX); return; } else @@ -570,7 +549,7 @@ SurfaceFit::SurfaceFit() float SurfaceFit::Fit() { - float fResult = FLOAT_MAX; + float fResult = FLT_MAX; if (CountPoints() > 0) { fResult = float(PolynomFit()); @@ -615,30 +594,13 @@ bool SurfaceFit::GetCurvatureInfo(double x, double y, double z, double &rfCurv0, double SurfaceFit::PolynomFit() { - if (PlaneFit::Fit() >= FLOAT_MAX) - return double(FLOAT_MAX); + if (PlaneFit::Fit() >= FLT_MAX) + return double(FLT_MAX); Base::Vector3d bs = Base::convertTo(this->_vBase); Base::Vector3d ex = Base::convertTo(this->_vDirU); Base::Vector3d ey = Base::convertTo(this->_vDirV); - //Base::Vector3d ez = Base::convertTo(this->_vDirW); - - // A*x = b - // See also www.cs.jhu.edu/~misha/Fall05/10.23.05.pdf - // z = f(x,y) = a*x^2 + b*y^2 + c*x*y + d*x + e*y + f - // z = P * Vi with Vi=(xi^2,yi^2,xiyi,xi,yi,1) and P=(a,b,c,d,e,f) - // To get the best-fit values the sum needs to be minimized: - // S = sum[(z-zi)^2} -> min with zi=z coordinates of the given points - // <=> S = sum[z^2 - 2*z*zi + zi^2] -> min - // <=> S(P) = sum[(P*Vi)^2 - 2*(P*Vi)*zi + zi^2] -> min - // To get the optimum the gradient of the expression must be the null vector - // Note: grad F(P) = (P*Vi)^2 = 2*(P*Vi)*Vi - // grad G(P) = -2*(P*Vi)*zi = -2*Vi*zi - // grad H(P) = zi^2 = 0 - // => grad S(P) = sum[2*(P*Vi)*Vi - 2*Vi*zi] = 0 - // <=> sum[(P*Vi)*Vi] = sum[Vi*zi] - // <=> sum[(Vi*Vi^t)*P] = sum[Vi*zi] where (Vi*Vi^t) is a symmetric matrix - // <=> sum[(Vi*Vi^t)]*P = sum[Vi*zi] + Eigen::Matrix A = Eigen::Matrix::Zero(); Eigen::Matrix b = Eigen::Matrix::Zero(); Eigen::Matrix x = Eigen::Matrix::Zero(); @@ -720,28 +682,6 @@ double SurfaceFit::PolynomFit() Eigen::HouseholderQR< Eigen::Matrix > qr(A); x = qr.solve(b); - // FunctionContainer gets an implicit function F(x,y,z) = 0 of this form - // _fCoeff[0] + - // _fCoeff[1]*x + _fCoeff[2]*y + _fCoeff[3]*z + - // _fCoeff[4]*x^2 + _fCoeff[5]*y^2 + _fCoeff[6]*z^2 + - // _fCoeff[7]*x*y + _fCoeff[8]*x*z + _fCoeff[9]*y*z - // - // The bivariate polynomial surface we get here is of the form - // z = f(x,y) = a*x^2 + b*y^2 + c*x*y + d*x + e*y + f - // Writing it as implicit surface F(x,y,z) = 0 gives this form - // F(x,y,z) = f(x,y) - z = a*x^2 + b*y^2 + c*x*y + d*x + e*y - z + f - // Thus: - // _fCoeff[0] = f - // _fCoeff[1] = d - // _fCoeff[2] = e - // _fCoeff[3] = -1 - // _fCoeff[4] = a - // _fCoeff[5] = b - // _fCoeff[6] = 0 - // _fCoeff[7] = c - // _fCoeff[8] = 0 - // _fCoeff[9] = 0 - _fCoeff[0] = x(5); _fCoeff[1] = x(3); _fCoeff[2] = x(4); @@ -1021,38 +961,7 @@ CylinderFit::CylinderFit() Base::Vector3f CylinderFit::GetInitialAxisFromNormals(const std::vector& n) const { -#if 0 - int nc = 0; - double x = 0.0; - double y = 0.0; - double z = 0.0; - for (int i = 0; i < (int)n.size()-1; ++i) { - for (int j = i+1; j < (int)n.size(); ++j) { - Base::Vector3f cross = n[i] % n[j]; - if (cross.Sqr() > 1.0e-6) { - cross.Normalize(); - x += cross.x; - y += cross.y; - z += cross.z; - ++nc; - } - } - } - if (nc > 0) { - x /= (double)nc; - y /= (double)nc; - z /= (double)nc; - Base::Vector3f axis(x,y,z); - axis.Normalize(); - return axis; - } - - PlaneFit planeFit; - planeFit.AddPoints(n); - planeFit.Fit(); - return planeFit.GetNormal(); -#endif // Like a plane fit where the base is at (0,0,0) double sxx,sxy,sxz,syy,syz,szz; @@ -1089,7 +998,7 @@ void CylinderFit::SetInitialValues(const Base::Vector3f& b, const Base::Vector3f float CylinderFit::Fit() { if (CountPoints() < 7) - return FLOAT_MAX; + return FLT_MAX; _bIsFitted = true; #if 1 @@ -1100,7 +1009,7 @@ float CylinderFit::Fit() cylFit.SetApproximations(_fRadius, Base::Vector3d(_vBase.x, _vBase.y, _vBase.z), Base::Vector3d(_vAxis.x, _vAxis.y, _vAxis.z)); float result = cylFit.Fit(); - if (result < FLOAT_MAX) { + if (result < FLT_MAX) { Base::Vector3d base = cylFit.GetBase(); Base::Vector3d dir = cylFit.GetAxis(); @@ -1189,7 +1098,7 @@ Base::Vector3f CylinderFit::GetAxis() const float CylinderFit::GetDistanceToCylinder(const Base::Vector3f &rcPoint) const { - float fResult = FLOAT_MAX; + float fResult = FLT_MAX; if (_bIsFitted) fResult = rcPoint.DistanceToLine(_vBase, _vAxis) - _fRadius; return fResult; @@ -1202,7 +1111,7 @@ float CylinderFit::GetStdDeviation() const // Standard deviation: SD=SQRT(VAR) // Standard error of the mean: SE=SD/SQRT(N) if (!_bIsFitted) - return FLOAT_MAX; + return FLT_MAX; float fSumXi = 0.0f, fSumXi2 = 0.0f, fMean = 0.0f, fDist = 0.0f; @@ -1289,7 +1198,7 @@ float SphereFit::GetRadius() const if (_bIsFitted) return _fRadius; else - return FLOAT_MAX; + return FLT_MAX; } Base::Vector3f SphereFit::GetCenter() const @@ -1304,7 +1213,7 @@ float SphereFit::Fit() { _bIsFitted = true; if (CountPoints() < 4) - return FLOAT_MAX; + return FLT_MAX; std::vector input; std::transform(_vPoints.begin(), _vPoints.end(), std::back_inserter(input), @@ -1327,7 +1236,7 @@ float SphereFit::Fit() sphereFit.AddPoints(_vPoints); sphereFit.ComputeApproximations(); float result = sphereFit.Fit(); - if (result < FLOAT_MAX) { + if (result < FLT_MAX) { Base::Vector3d center = sphereFit.GetCenter(); #if defined(_DEBUG) Base::Console().Message("MeshCoreFit::Sphere Fit: Center: (%0.4f, %0.4f, %0.4f), Radius: %0.4f, Std Dev: %0.4f, Iterations: %d\n", @@ -1343,7 +1252,7 @@ float SphereFit::Fit() float SphereFit::GetDistanceToSphere(const Base::Vector3f& rcPoint) const { - float fResult = FLOAT_MAX; + float fResult = FLT_MAX; if (_bIsFitted) { fResult = Base::Vector3f(rcPoint - _vCenter).Length() - _fRadius; } @@ -1357,7 +1266,7 @@ float SphereFit::GetStdDeviation() const // Standard deviation: SD=SQRT(VAR) // Standard error of the mean: SE=SD/SQRT(N) if (!_bIsFitted) - return FLOAT_MAX; + return FLT_MAX; float fSumXi = 0.0f, fSumXi2 = 0.0f, fMean = 0.0f, fDist = 0.0f; @@ -1423,7 +1332,7 @@ float PolynomialFit::Fit() _fCoeff[i] = coeff[i]; } catch (const std::exception&) { - return FLOAT_MAX; + return FLT_MAX; } return 0.0f; diff --git a/src/Mod/Mesh/App/Core/Approximation.h b/src/Mod/Mesh/App/Core/Approximation.h index a7e3ac60e385e..c7d371665dc04 100644 --- a/src/Mod/Mesh/App/Core/Approximation.h +++ b/src/Mod/Mesh/App/Core/Approximation.h @@ -172,7 +172,7 @@ class MeshExport Approximation //NOLINTBEGIN std::list< Base::Vector3f > _vPoints; /**< Holds the points for the fit algorithm. */ bool _bIsFitted{false}; /**< Flag, whether the fit has been called. */ - float _fLastResult{FLOAT_MAX}; /**< Stores the last result of the fit */ + float _fLastResult{FLT_MAX}; /**< Stores the last result of the fit */ //NOLINTEND }; @@ -195,22 +195,22 @@ class MeshExport PlaneFit : public Approximation Base::Vector3f GetNormal() const; /** * Fit a plane into the given points. We must have at least three non-collinear points - * to succeed. If the fit fails FLOAT_MAX is returned. + * to succeed. If the fit fails FLT_MAX is returned. */ float Fit() override; /** * Returns the distance from the point \a rcPoint to the fitted plane. If Fit() has not been - * called FLOAT_MAX is returned. + * called FLT_MAX is returned. */ float GetDistanceToPlane(const Base::Vector3f &rcPoint) const; /** * Returns the standard deviation from the points to the fitted plane. If Fit() has not been - * called FLOAT_MAX is returned. + * called FLT_MAX is returned. */ float GetStdDeviation() const; /** * Returns the standard deviation from the points to the fitted plane with respect to the orientation - * of the plane's normal. If Fit() has not been called FLOAT_MAX is returned. + * of the plane's normal. If Fit() has not been called FLT_MAX is returned. */ float GetSignedStdDeviation() const; /** @@ -376,17 +376,17 @@ class MeshExport CylinderFit : public Approximation */ Base::Vector3f GetInitialAxisFromNormals(const std::vector& n) const; /** - * Fit a cylinder into the given points. If the fit fails FLOAT_MAX is returned. + * Fit a cylinder into the given points. If the fit fails FLT_MAX is returned. */ float Fit() override; /** * Returns the distance from the point \a rcPoint to the fitted cylinder. If Fit() has not been - * called FLOAT_MAX is returned. + * called FLT_MAX is returned. */ float GetDistanceToCylinder(const Base::Vector3f &rcPoint) const; /** * Returns the standard deviation from the points to the fitted cylinder. If Fit() has not been - * called FLOAT_MAX is returned. + * called FLT_MAX is returned. */ float GetStdDeviation() const; /** @@ -418,17 +418,17 @@ class MeshExport SphereFit : public Approximation float GetRadius() const; Base::Vector3f GetCenter() const; /** - * Fit a sphere into the given points. If the fit fails FLOAT_MAX is returned. + * Fit a sphere into the given points. If the fit fails FLT_MAX is returned. */ float Fit() override; /** * Returns the distance from the point \a rcPoint to the fitted sphere. If Fit() has not been - * called FLOAT_MAX is returned. + * called FLT_MAX is returned. */ float GetDistanceToSphere(const Base::Vector3f &rcPoint) const; /** * Returns the standard deviation from the points to the fitted sphere. If Fit() has not been - * called FLOAT_MAX is returned. + * called FLT_MAX is returned. */ float GetStdDeviation() const; /** diff --git a/src/Mod/Mesh/App/Core/CylinderFit.cpp b/src/Mod/Mesh/App/Core/CylinderFit.cpp index 3ccdbec12219e..b45e8652b51fe 100644 --- a/src/Mod/Mesh/App/Core/CylinderFit.cpp +++ b/src/Mod/Mesh/App/Core/CylinderFit.cpp @@ -79,7 +79,7 @@ CylinderFit::CylinderFit() void CylinderFit::SetApproximations(double radius, const Base::Vector3d &base, const Base::Vector3d &axis) { _bIsFitted = false; - _fLastResult = FLOAT_MAX; + _fLastResult = FLT_MAX; _numIter = 0; _dRadius = radius; _vBase = base; @@ -92,7 +92,7 @@ void CylinderFit::SetApproximations(double radius, const Base::Vector3d &base, c void CylinderFit::SetApproximations(const Base::Vector3d &base, const Base::Vector3d &axis) { _bIsFitted = false; - _fLastResult = FLOAT_MAX; + _fLastResult = FLT_MAX; _numIter = 0; _vBase = base; _vAxis = axis; @@ -155,7 +155,7 @@ int CylinderFit::GetNumIterations() const float CylinderFit::GetDistanceToCylinder(const Base::Vector3f &rcPoint) const { - float fResult = FLOAT_MAX; + float fResult = FLT_MAX; if (_bIsFitted) { fResult = Base::Vector3d(rcPoint.x, rcPoint.y, rcPoint.z).DistanceToLine(_vBase, _vAxis) - _dRadius; @@ -169,7 +169,7 @@ float CylinderFit::GetStdDeviation() const // Variance: VAR=(N/N-1)*[(1/N)*SUM(Xi^2)-M^2] // Standard deviation: SD=SQRT(VAR) if (!_bIsFitted) - return FLOAT_MAX; + return FLT_MAX; double sumXi = 0.0, sumXi2 = 0.0, dist = 0.0; for (auto it : _vPoints) { @@ -224,7 +224,7 @@ void CylinderFit::ProjectToCylinder() void CylinderFit::ComputeApproximationsLine() { _bIsFitted = false; - _fLastResult = FLOAT_MAX; + _fLastResult = FLT_MAX; _numIter = 0; _vBase.Set(0.0, 0.0, 0.0); _vAxis.Set(0.0, 0.0, 0.0); @@ -247,12 +247,12 @@ void CylinderFit::ComputeApproximationsLine() float CylinderFit::Fit() { _bIsFitted = false; - _fLastResult = FLOAT_MAX; + _fLastResult = FLT_MAX; _numIter = 0; // A minimum of 5 surface points is needed to define a cylinder if (CountPoints() < 5) - return FLOAT_MAX; + return FLT_MAX; // If approximations have not been set/computed then compute some now using the line fit method if (_dRadius == 0.0) @@ -286,7 +286,7 @@ float CylinderFit::Fit() // Solve the equations for the unknown corrections Eigen::LLT< Matrix5x5 > llt(atpa); if (llt.info() != Eigen::Success) - return FLOAT_MAX; + return FLT_MAX; Eigen::VectorXd x = llt.solve(atpl); // Check parameter convergence @@ -299,18 +299,18 @@ float CylinderFit::Fit() // Before updating the unknowns, compute the residuals and sigma0 and check the residual convergence bool vConverged; if (!computeResiduals(solDir, x, residuals, sigma0, _vConvLimit, vConverged)) - return FLOAT_MAX; + return FLT_MAX; if (!vConverged) cont = true; // Update the parameters if (!updateParameters(solDir, x)) - return FLOAT_MAX; + return FLT_MAX; } // Check for convergence if (cont) - return FLOAT_MAX; + return FLT_MAX; _bIsFitted = true; _fLastResult = sigma0; diff --git a/src/Mod/Mesh/App/Core/CylinderFit.h b/src/Mod/Mesh/App/Core/CylinderFit.h index 72d3ad0bdacab..7dd530655afc6 100644 --- a/src/Mod/Mesh/App/Core/CylinderFit.h +++ b/src/Mod/Mesh/App/Core/CylinderFit.h @@ -81,17 +81,17 @@ class MeshExport CylinderFit : public MeshCore::Approximation */ int GetNumIterations() const; /** - * Fit a cylinder into the given points. If the fit fails FLOAT_MAX is returned. + * Fit a cylinder into the given points. If the fit fails FLT_MAX is returned. */ float Fit() override; /** * Returns the distance from the point \a rcPoint to the fitted cylinder. If Fit() has not been - * called FLOAT_MAX is returned. + * called FLT_MAX is returned. */ float GetDistanceToCylinder(const Base::Vector3f &rcPoint) const; /** * Returns the standard deviation from the points to the fitted cylinder. If Fit() has not been - * called FLOAT_MAX is returned. + * called FLT_MAX is returned. */ float GetStdDeviation() const; /** diff --git a/src/Mod/Mesh/App/Core/Definitions.h b/src/Mod/Mesh/App/Core/Definitions.h index d1ef6ab3297f9..19fc3954c79d4 100644 --- a/src/Mod/Mesh/App/Core/Definitions.h +++ b/src/Mod/Mesh/App/Core/Definitions.h @@ -36,22 +36,7 @@ #define MESH_REMOVE_MIN_LEN true #define MESH_REMOVE_G3_EDGES true -/* - * general constant definitions - */ -#define FLOAT_EPS 1.0e-4f - -#ifndef FLOAT_MAX -# define FLOAT_MAX 1e30f -#endif -#ifndef DOUBLE_MAX -# define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ -#endif - -#ifndef DOUBLE_MIN -# define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ -#endif namespace MeshCore { diff --git a/src/Mod/Mesh/App/Core/Elements.cpp b/src/Mod/Mesh/App/Core/Elements.cpp index 4cfa55398f92b..b3cd49b7a5ee6 100644 --- a/src/Mod/Mesh/App/Core/Elements.cpp +++ b/src/Mod/Mesh/App/Core/Elements.cpp @@ -232,7 +232,7 @@ bool MeshGeomEdge::IntersectWithLine (const Base::Vector3f &rclPt, const float eps = 1e-06f; Base::Vector3f n = _aclPoints[1] - _aclPoints[0]; - // check angle between edge and the line direction, FLOAT_MAX is + // check angle between edge and the line direction, FLT_MAX is // returned for degenerated edges float fAngle = rclDir.GetAngle(n); if (fAngle == 0) { @@ -376,7 +376,7 @@ void MeshGeomEdge::ClosestPointsToLine(const Base::Vector3f &linePt, const Base: const float eps = 1e-06f; Base::Vector3f edgeDir = _aclPoints[1] - _aclPoints[0]; - // check angle between edge and the line direction, FLOAT_MAX is + // check angle between edge and the line direction, FLT_MAX is // returned for degenerated edges float fAngle = lineDir.GetAngle(edgeDir); if (fAngle == 0) { @@ -853,7 +853,7 @@ bool MeshGeomFacet::Foraminate (const Base::Vector3f &P, const Base::Vector3f &d const float eps = 1e-06f; Base::Vector3f n = this->GetNormal(); - // check angle between facet normal and the line direction, FLOAT_MAX is + // check angle between facet normal and the line direction, FLT_MAX is // returned for degenerated facets float fAngle = dir.GetAngle(n); if (fAngle > fMaxAngle) @@ -1253,9 +1253,9 @@ unsigned short MeshGeomFacet::NearestEdgeToPoint(const Base::Vector3f& rclPt) co const Base::Vector3f& rcP2 = _aclPoints[1]; const Base::Vector3f& rcP3 = _aclPoints[2]; - float fD1 = FLOAT_MAX; - float fD2 = FLOAT_MAX; - float fD3 = FLOAT_MAX; + float fD1 = FLT_MAX; + float fD2 = FLT_MAX; + float fD3 = FLT_MAX; // 1st edge Base::Vector3f clDir = rcP2 - rcP1; @@ -1322,9 +1322,9 @@ void MeshGeomFacet::NearestEdgeToPoint(const Base::Vector3f& rclPt, float& fDist const Base::Vector3f& rcP2 = _aclPoints[1]; const Base::Vector3f& rcP3 = _aclPoints[2]; - float fD1 = FLOAT_MAX; - float fD2 = FLOAT_MAX; - float fD3 = FLOAT_MAX; + float fD1 = FLT_MAX; + float fD2 = FLT_MAX; + float fD3 = FLT_MAX; // 1st edge Base::Vector3f clDir = rcP2 - rcP1; diff --git a/src/Mod/Mesh/App/Core/Grid.cpp b/src/Mod/Mesh/App/Core/Grid.cpp index 1a4dc27db0698..cbc00d4ea1b39 100644 --- a/src/Mod/Mesh/App/Core/Grid.cpp +++ b/src/Mod/Mesh/App/Core/Grid.cpp @@ -780,7 +780,7 @@ void MeshFacetGrid::RebuildGrid () unsigned long MeshFacetGrid::SearchNearestFromPoint (const Base::Vector3f &rclPt) const { ElementIndex ulFacetInd = ELEMENT_INDEX_MAX; - float fMinDist = FLOAT_MAX; + float fMinDist = FLT_MAX; Base::BoundBox3f clBB = GetBoundBox(); if (clBB.IsInBox(rclPt)) @@ -1162,7 +1162,7 @@ bool MeshGridIterator::InitOnRay (const Base::Vector3f &rclPt, const Base::Vecto // needed in NextOnRay() to avoid an infinite loop _cSearchPositions.clear(); - _fMaxSearchArea = FLOAT_MAX; + _fMaxSearchArea = FLT_MAX; raulElements.clear(); diff --git a/src/Mod/Mesh/App/Core/Grid.h b/src/Mod/Mesh/App/Core/Grid.h index 3873ec3177e85..922988bd82bce 100644 --- a/src/Mod/Mesh/App/Core/Grid.h +++ b/src/Mod/Mesh/App/Core/Grid.h @@ -339,7 +339,7 @@ class MeshExport MeshGridIterator Base::Vector3f _clPt; /**< Base point of search ray. */ Base::Vector3f _clDir; /**< Direction of search ray. */ bool _bValidRay{false}; /**< Search ray ok? */ - float _fMaxSearchArea{FLOAT_MAX}; + float _fMaxSearchArea{FLT_MAX}; /** Checks if a grid position is already visited by NextOnRay(). */ struct GridElement { diff --git a/src/Mod/Mesh/App/Core/Projection.cpp b/src/Mod/Mesh/App/Core/Projection.cpp index cd80d9b6c4b34..6545bf11dfa51 100644 --- a/src/Mod/Mesh/App/Core/Projection.cpp +++ b/src/Mod/Mesh/App/Core/Projection.cpp @@ -77,8 +77,8 @@ bool MeshProjection::connectLines(std::list< std::pair& polyline) const { - const float fMaxDist = float(sqrt(FLOAT_MAX)); // max. length of a gap - const float fMinEps = 1.0e-4f; + const float fMaxDist = float(sqrt(FLT_MAX)); // max. length of a gap + const float fMinEps = FLT_EPSILON; polyline.clear(); polyline.push_back(startPoint); @@ -181,8 +181,6 @@ bool MeshProjection::projectLineOnMesh(const MeshFacetGrid& grid, cutLine.emplace_back(v1, e2); else cutLine.emplace_back(v1, e1); - - //start = it - facets.begin(); } if (facet == f2) { // end facet @@ -190,8 +188,6 @@ bool MeshProjection::projectLineOnMesh(const MeshFacetGrid& grid, cutLine.emplace_back(v2, e2); else cutLine.emplace_back(v2, e1); - - //end = it - facets.begin(); } } } diff --git a/src/Mod/Mesh/App/Core/Segmentation.cpp b/src/Mod/Mesh/App/Core/Segmentation.cpp index df265d0359fb7..0dd1183ee312b 100644 --- a/src/Mod/Mesh/App/Core/Segmentation.cpp +++ b/src/Mod/Mesh/App/Core/Segmentation.cpp @@ -198,7 +198,7 @@ CylinderSurfaceFit::CylinderSurfaceFit() : fitter(new CylinderFit) { axis.Set(0,0,0); - radius = FLOAT_MAX; + radius = FLT_MAX; } /*! @@ -260,7 +260,7 @@ float CylinderSurfaceFit::Fit() return 0; float fit = fitter->Fit(); - if (fit < FLOAT_MAX) { + if (fit < FLT_MAX) { basepoint = fitter->GetBase(); axis = fitter->GetAxis(); radius = fitter->GetRadius(); @@ -306,7 +306,7 @@ SphereSurfaceFit::SphereSurfaceFit() : fitter(new SphereFit) { center.Set(0,0,0); - radius = FLOAT_MAX; + radius = FLT_MAX; } SphereSurfaceFit::SphereSurfaceFit(const Base::Vector3f& c, float r) @@ -362,7 +362,7 @@ float SphereSurfaceFit::Fit() return 0; float fit = fitter->Fit(); - if (fit < FLOAT_MAX) { + if (fit < FLT_MAX) { center = fitter->GetCenter(); radius = fitter->GetRadius(); } diff --git a/src/Mod/Mesh/App/Core/SphereFit.cpp b/src/Mod/Mesh/App/Core/SphereFit.cpp index f87a8c72c935b..5ce70a0ea1ee8 100644 --- a/src/Mod/Mesh/App/Core/SphereFit.cpp +++ b/src/Mod/Mesh/App/Core/SphereFit.cpp @@ -41,7 +41,7 @@ SphereFit::SphereFit() void SphereFit::SetApproximations(double radius, const Base::Vector3d ¢er) { _bIsFitted = false; - _fLastResult = FLOAT_MAX; + _fLastResult = FLT_MAX; _numIter = 0; _dRadius = radius; _vCenter = center; @@ -86,7 +86,7 @@ int SphereFit::GetNumIterations() const float SphereFit::GetDistanceToSphere(const Base::Vector3f &rcPoint) const { - float fResult = FLOAT_MAX; + float fResult = FLT_MAX; if (_bIsFitted) { fResult = Base::Vector3d((double)rcPoint.x - _vCenter.x, (double)rcPoint.y - _vCenter.y, (double)rcPoint.z - _vCenter.z).Length() - _dRadius; @@ -100,7 +100,7 @@ float SphereFit::GetStdDeviation() const // Variance: VAR=(N/N-1)*[(1/N)*SUM(Xi^2)-M^2] // Standard deviation: SD=SQRT(VAR) if (!_bIsFitted) - return FLOAT_MAX; + return FLT_MAX; double sumXi = 0.0, sumXi2 = 0.0, dist = 0.0; for (auto it : _vPoints) { @@ -146,7 +146,7 @@ void SphereFit::ProjectToSphere() void SphereFit::ComputeApproximations() { _bIsFitted = false; - _fLastResult = FLOAT_MAX; + _fLastResult = FLT_MAX; _numIter = 0; _vCenter.Set(0.0, 0.0, 0.0); _dRadius = 0.0; @@ -173,12 +173,12 @@ void SphereFit::ComputeApproximations() float SphereFit::Fit() { _bIsFitted = false; - _fLastResult = FLOAT_MAX; + _fLastResult = FLT_MAX; _numIter = 0; // A minimum of 4 surface points is needed to define a sphere if (CountPoints() < 4) - return FLOAT_MAX; + return FLT_MAX; // If approximations have not been set/computed then compute some now if (_dRadius == 0.0) @@ -202,7 +202,7 @@ float SphereFit::Fit() // Solve the equations for the unknown corrections Eigen::LLT< Matrix4x4 > llt(atpa); if (llt.info() != Eigen::Success) - return FLOAT_MAX; + return FLT_MAX; Eigen::VectorXd x = llt.solve(atpl); // Check parameter convergence (order of parameters: X,Y,Z,R) @@ -214,7 +214,7 @@ float SphereFit::Fit() // Before updating the unknowns, compute the residuals and sigma0 and check the residual convergence bool vConverged; if (!computeResiduals(x, residuals, sigma0, _vConvLimit, vConverged)) - return FLOAT_MAX; + return FLT_MAX; if (!vConverged) cont = true; @@ -227,7 +227,7 @@ float SphereFit::Fit() // Check for convergence if (cont) - return FLOAT_MAX; + return FLT_MAX; _bIsFitted = true; _fLastResult = sigma0; diff --git a/src/Mod/Mesh/App/Core/SphereFit.h b/src/Mod/Mesh/App/Core/SphereFit.h index 64c2e80a254d7..498d6c2ed31f5 100644 --- a/src/Mod/Mesh/App/Core/SphereFit.h +++ b/src/Mod/Mesh/App/Core/SphereFit.h @@ -69,17 +69,17 @@ class MeshExport SphereFit : public MeshCore::Approximation */ void ComputeApproximations(); /** - * Fit a sphere onto the given points. If the fit fails FLOAT_MAX is returned. + * Fit a sphere onto the given points. If the fit fails FLT_MAX is returned. */ float Fit() override; /** * Returns the distance from the point \a rcPoint to the fitted sphere. If Fit() has not been - * called FLOAT_MAX is returned. + * called FLT_MAX is returned. */ float GetDistanceToSphere(const Base::Vector3f &rcPoint) const; /** * Returns the standard deviation from the points to the fitted sphere. If Fit() has not been - * called FLOAT_MAX is returned. + * called FLT_MAX is returned. */ float GetStdDeviation() const; /** diff --git a/src/Mod/Mesh/App/Core/Tools.h b/src/Mod/Mesh/App/Core/Tools.h index 9920e1d7ee9a5..4293d4e6a9a2a 100644 --- a/src/Mod/Mesh/App/Core/Tools.h +++ b/src/Mod/Mesh/App/Core/Tools.h @@ -186,7 +186,7 @@ class MeshNearestIndexToPlane } Index nearest_index; - float nearest_dist{FLOAT_MAX}; + float nearest_dist{FLT_MAX}; private: T it; diff --git a/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp b/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp index e33d338304839..dac4829d0eaf0 100644 --- a/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp +++ b/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp @@ -117,7 +117,7 @@ bool MeshTopoAlgorithm::SnapVertex(FacetIndex ulFacetPos, const Base::Vector3f& float fTV = (rP-rPt1) * (rPt2-rPt1); // Point is on the edge - if ( cNo3.Length() < FLOAT_EPS ) + if ( cNo3.Length() < FLT_EPSILON ) { return SplitOpenEdge(ulFacetPos, i, rP); } @@ -749,11 +749,11 @@ bool MeshTopoAlgorithm::SplitOpenEdge(FacetIndex ulFacetPos, unsigned short uSid bool MeshTopoAlgorithm::Vertex_Less::operator ()(const Base::Vector3f& u, const Base::Vector3f& v) const { - if (fabs (u.x - v.x) > FLOAT_EPS) + if (fabs (u.x - v.x) > FLT_EPSILON) return u.x < v.x; - if (fabs (u.y - v.y) > FLOAT_EPS) + if (fabs (u.y - v.y) > FLT_EPSILON) return u.y < v.y; - if (fabs (u.z - v.z) > FLOAT_EPS) + if (fabs (u.z - v.z) > FLT_EPSILON) return u.z < v.z; return false; } @@ -1143,7 +1143,7 @@ void MeshTopoAlgorithm::SplitFacet(FacetIndex ulFacetPos, const Base::Vector3f& void MeshTopoAlgorithm::SplitFacetOnOneEdge(FacetIndex ulFacetPos, const Base::Vector3f& rP) { - float fMinDist = FLOAT_MAX; + float fMinDist = FLT_MAX; unsigned short iEdgeNo = USHRT_MAX; MeshFacet& rFace = _rclMesh._aclFacetArray[ulFacetPos]; @@ -1171,7 +1171,7 @@ void MeshTopoAlgorithm::SplitFacetOnTwoEdges(FacetIndex ulFacetPos, const Base:: { // search for the matching edges unsigned short iEdgeNo1 = USHRT_MAX, iEdgeNo2 = USHRT_MAX; - float fMinDist1 = FLOAT_MAX, fMinDist2 = FLOAT_MAX; + float fMinDist1 = FLT_MAX, fMinDist2 = FLT_MAX; MeshFacet& rFace = _rclMesh._aclFacetArray[ulFacetPos]; for (unsigned short i=0; i<3; i++) { diff --git a/src/Mod/Mesh/App/Core/Triangulation.cpp b/src/Mod/Mesh/App/Core/Triangulation.cpp index 0816b408638bc..8604ae2ce2719 100644 --- a/src/Mod/Mesh/App/Core/Triangulation.cpp +++ b/src/Mod/Mesh/App/Core/Triangulation.cpp @@ -141,7 +141,7 @@ Base::Matrix4D AbstractPolygonTriangulator::GetTransformToFitPlane() const for (auto point : _points) planeFit.AddPoint(point); - if (planeFit.Fit() >= FLOAT_MAX) + if (planeFit.Fit() >= FLT_MAX) throw Base::RuntimeError("Plane fit failed"); Base::Vector3f bs = planeFit.GetBase(); @@ -210,7 +210,7 @@ void AbstractPolygonTriangulator::PostProcessing(const std::vector= uMinPts && polyFit.Fit() < FLOAT_MAX) { + if (polyFit.CountPoints() >= uMinPts && polyFit.Fit() < FLT_MAX) { for (auto & newpoint : _newpoints) newpoint.z = static_cast(polyFit.Value(newpoint.x, newpoint.y)); } @@ -356,7 +356,7 @@ bool EarClippingTriangulator::Triangulate::InsideTriangle(float Ax, float Ay, fl cCROSSap = cx*apy - cy*apx; bCROSScp = bx*cpy - by*cpx; - return ((aCROSSbp >= FLOAT_EPS) && (bCROSScp >= FLOAT_EPS) && (cCROSSap >= FLOAT_EPS)); + return ((aCROSSbp >= FLT_EPSILON) && (bCROSScp >= FLT_EPSILON) && (cCROSSap >= FLT_EPSILON)); } bool EarClippingTriangulator::Triangulate::Snip(const std::vector &contour, @@ -374,7 +374,7 @@ bool EarClippingTriangulator::Triangulate::Snip(const std::vector (((Bx-Ax)*(Cy-Ay)) - ((By-Ay)*(Cx-Ax)))) + if (FLT_EPSILON > (((Bx-Ax)*(Cy-Ay)) - ((By-Ay)*(Cx-Ax)))) return false; for (p=0;p values; MeshCore::PlaneFit fit; fit.AddPoints(pts.points); - if (fit.Fit() < FLOAT_MAX) { + if (fit.Fit() < FLT_MAX) { Base::Vector3f base = fit.GetBase(); Base::Vector3f axis = fit.GetNormal(); values.push_back(base.x); @@ -89,7 +89,7 @@ class CylinderFitParameter : public FitParameter #endif } - if (fit.Fit() < FLOAT_MAX) { + if (fit.Fit() < FLT_MAX) { Base::Vector3f base, top; fit.GetBounding(base, top); Base::Vector3f axis = fit.GetAxis(); @@ -134,7 +134,7 @@ class SphereFitParameter : public FitParameter std::vector values; MeshCore::SphereFit fit; fit.AddPoints(pts.points); - if (fit.Fit() < FLOAT_MAX) { + if (fit.Fit() < FLT_MAX) { Base::Vector3f base = fit.GetCenter(); float radius = fit.GetRadius(); values.push_back(base.x); diff --git a/src/Mod/MeshPart/App/CurveProjector.cpp b/src/Mod/MeshPart/App/CurveProjector.cpp index 703813ab68a73..d9e97585b485c 100644 --- a/src/Mod/MeshPart/App/CurveProjector.cpp +++ b/src/Mod/MeshPart/App/CurveProjector.cpp @@ -182,7 +182,7 @@ void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, / ((cP1 - cP0) * (cP1 - cP0)); // is the Point on the Edge of the facet? if (l < 0.0 || l > 1.0) { - PointOnEdge[i] = Base::Vector3f(FLOAT_MAX, 0, 0); + PointOnEdge[i] = Base::Vector3f(FLT_MAX, 0, 0); } else { cSplitPoint = (1 - l) * cP0 + l * cP1; @@ -193,11 +193,11 @@ void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, // no intersection } else if (Alg.NbPoints() == 0) { - PointOnEdge[i] = Base::Vector3f(FLOAT_MAX, 0, 0); + PointOnEdge[i] = Base::Vector3f(FLT_MAX, 0, 0); // more the one intersection (@ToDo) } else if (Alg.NbPoints() > 1) { - PointOnEdge[i] = Base::Vector3f(FLOAT_MAX, 0, 0); + PointOnEdge[i] = Base::Vector3f(FLT_MAX, 0, 0); Base::Console().Log("MeshAlgos::projectCurve(): More then one intersection in " "Facet %lu, Edge %d\n", uCurFacetIdx, @@ -236,7 +236,7 @@ bool CurveProjectorShape::findStartPoint(const MeshKernel& MeshK, MeshCore::FacetIndex& FaceIndex) { Base::Vector3f TempResultPoint; - float MinLength = FLOAT_MAX; + float MinLength = FLT_MAX; bool bHit = false; // go through the whole Mesh @@ -313,8 +313,6 @@ void CurveProjectorSimple::projectCurve(const TopoDS_Edge& aEdge, { Base::Vector3f /*cResultPoint, cSplitPoint, cPlanePnt, cPlaneNormal,*/ TempResultPoint; bool bFirst = true; - // unsigned long auNeighboursIdx[3]; - // std::map >::iterator N1,N2,N3; Standard_Real fBegin, fEnd; Handle(Geom_Curve) hCurve = BRep_Tool::Curve(aEdge, fBegin, fEnd); @@ -361,189 +359,8 @@ void CurveProjectorSimple::projectCurve(const TopoDS_Edge& aEdge, Base::Console().Log("Projection map [%d facets with %d points]\n", FaceProjctMap.size(), PointCount); - - // estimate the first face - // gp_Pnt gpPt = hCurve->Value(fBegin); - // if( - // !findStartPoint(MeshK,Base::Vector3f(gpPt.X(),gpPt.Y(),gpPt.Z()),cResultPoint,uCurFacetIdx) - // ) - // uCurFacetIdx = FaceProjctMap.begin()->first; - - /* - do{ - Base::Console().Log("Grow on %d %d left\n",uCurFacetIdx,FaceProjctMap.size()); - - if(FaceProjctMap[uCurFacetIdx].size() == 1) - { - Base::Console().Log("Single hit\n"); - }else{ - - - } - - FaceProjctMap.erase(uCurFacetIdx); - - // estimate next facet - MeshGeomFacet cCurFacet= MeshK.GetFacet(uCurFacetIdx); - MeshK.GetFacetNeighbours ( uCurFacetIdx, auNeighboursIdx[0], auNeighboursIdx[1], - auNeighboursIdx[2]); - - uCurFacetIdx = MeshCore::FACET_INDEX_MAX; - PointCount = 0; - - for(int i=0; i<3; i++) - { - N1 = FaceProjctMap.find(auNeighboursIdx[i]); - // if the i'th neighbour is valid - if ( N1 != FaceProjctMap.end() ) - { - unsigned long temp = N1->second.size(); - if(temp >= PointCount){ - PointCount = N1->second.size(); - uCurFacetIdx = auNeighboursIdx[i]; - } - } - } - - - }while(uCurFacetIdx != MeshCore::FACET_INDEX_MAX); - */ } -/* -void CurveProjectorSimple::projectCurve( const TopoDS_Edge& aEdge, - const std::vector &rclPoints, - std::vector &vSplitEdges) -{ - const MeshKernel &MeshK = *(_Mesh.getKernel()); - - Standard_Real fFirst, fLast, fAct; - Handle(Geom_Curve) hCurve = BRep_Tool::Curve( aEdge,fFirst,fLast ); - - // getting start point - gp_Pnt gpPt = hCurve->Value(fFirst); - fAct = fFirst; - // projection of the first point - Base::Vector3f cStartPoint = Base::Vector3f(gpPt.X(),gpPt.Y(),gpPt.Z()); - Base::Vector3f cResultPoint, cSplitPoint, cPlanePnt, cPlaneNormal,TempResultPoint; - MeshCore::FacetIndex uStartFacetIdx,uCurFacetIdx; - MeshCore::FacetIndex uLastFacetIdx=MeshCore::FACET_INDEX_MAX-1; // use another value as -FACET_INDEX_MAX MeshCore::FacetIndex auNeighboursIdx[3]; bool GoOn; - - // go through the whole Mesh, find the first projection - MeshFacetIterator It(MeshK); - GoOn = false; - for(It.Init();It.More();It.Next()) - { - // try to project (with angle) to the face - if(MeshFacetFunc::IntersectWithLine (*It, cStartPoint, It->GetNormal(), cResultPoint) ) - { - uCurFacetIdx = It.Position(); - GoOn = true; - break; - } - } - - if(!GoOn) - { - Base::Console().Log("Starting point not projectable\n"); - return; - } - { - float fStep = (fLast-fFirst)/20; - unsigned long HitCount,Sentinel = 0 ; - MeshGeomFacet cCurFacet= MeshK.GetFacet(uCurFacetIdx); - MeshK.GetFacetNeighbours ( uCurFacetIdx, auNeighboursIdx[0], auNeighboursIdx[1], -auNeighboursIdx[2]); - - do{ - // lower the step until you find a neigbourfacet to project... - fStep /= 2.0; - // still on the same facet? - gpPt = hCurve->Value(fAct+fStep); - if(MeshFacetFunc::IntersectWithLine (cCurFacet, Base::Vector3f(gpPt.X(),gpPt.Y(),gpPt.Z()), -cCurFacet.GetNormal(), cResultPoint) ) - { - fAct += fStep; - fStep *= 2.0; - continue; - } - - HitCount = 0; - for(int i=0; i<3; i++) - { - // if the i'th neighbour is valid - if ( auNeighboursIdx[i] != MeshCore::FACET_INDEX_MAX ) - { - // try to project next interval - MeshGeomFacet N = MeshK.GetFacet( auNeighboursIdx[i] ); - gpPt = hCurve->Value(fAct+fStep); - if(MeshFacetFunc::IntersectWithLine (*It, Base::Vector3f(gpPt.X(),gpPt.Y(),gpPt.Z()), -It->GetNormal(), cResultPoint) ) - { - HitCount++; - uStartFacetIdx = auNeighboursIdx[i]; - } - - } - } - - Sentinel++; - - }while(HitCount!=1 && Sentinel < 20); - - } - - -} -*/ -/* - -void CurveProjectorSimple::projectCurve( const TopoDS_Edge& aEdge, - const std::vector &rclPoints, - std::vector &vSplitEdges) -{ - const MeshKernel &MeshK = *(_Mesh.getKernel()); - - Standard_Real fFirst, fLast; - Handle(Geom_Curve) hCurve = BRep_Tool::Curve( aEdge,fFirst,fLast ); - - // getting start point - gp_Pnt gpPt = hCurve->Value(fFirst); - - // projection of the first point - Base::Vector3f cStartPoint = Base::Vector3f(gpPt.X(),gpPt.Y(),gpPt.Z()); - Base::Vector3f cResultPoint, cSplitPoint, cPlanePnt, cPlaneNormal; - MeshCore::FacetIndex uStartFacetIdx,uCurFacetIdx; - MeshCore::FacetIndex uLastFacetIdx=MeshCore::FACET_INDEX_MAX-1; // use another value as -FACET_INDEX_MAX MeshCore::FacetIndex auNeighboursIdx[3]; bool GoOn; - - if( !findStartPoint(MeshK,cStartPoint,cResultPoint,uStartFacetIdx) ) - return; - - FILE* file = fopen("projected.asc", "w"); - - // go through the whole Mesh - MeshFacetIterator It1(MeshK); - for(It1.Init();It1.More();It1.Next()) - { - // cycling through the points and find the first projecteble point ( if the curve starts outside -the mesh) for( std::vector::const_iterator It = -rclPoints.begin()+1;It!=rclPoints.end();++It) - { -// MeshGeomFacet facet = MeshK.GetFacet(uStartFacetIdx); - MeshGeomFacet facet = *It1; - - if(MeshFacetFunc::IntersectWithLine(facet, *It, facet.GetNormal(), cResultPoint) ) - fprintf(file, "%.4f %.4f %.4f\n", cResultPoint.x, cResultPoint.y, cResultPoint.z); - - } - } - - fclose(file); - -} -*/ bool CurveProjectorSimple::findStartPoint(const MeshKernel& MeshK, const Base::Vector3f& Pnt, @@ -551,7 +368,7 @@ bool CurveProjectorSimple::findStartPoint(const MeshKernel& MeshK, MeshCore::FacetIndex& FaceIndex) { Base::Vector3f TempResultPoint; - float MinLength = FLOAT_MAX; + float MinLength = FLT_MAX; bool bHit = false; // go through the whole Mesh @@ -653,11 +470,11 @@ void CurveProjectorWithToolMesh::makeToolMesh(const TopoDS_Edge& aEdge, // build up the new mesh - Base::Vector3f lp(FLOAT_MAX, 0, 0), ln, p1, p2, p3, p4, p5, p6; + Base::Vector3f lp(FLT_MAX, 0, 0), ln, p1, p2, p3, p4, p5, p6; float ToolSize = 0.2f; for (const auto& It2 : LineSegs) { - if (lp.x != FLOAT_MAX) { + if (lp.x != FLT_MAX) { p1 = lp + (ln * (-ToolSize)); p2 = lp + (ln * ToolSize); p3 = lp; diff --git a/src/Mod/Part/App/Attacher.cpp b/src/Mod/Part/App/Attacher.cpp index c102396cd6e15..2c3a8266f4faa 100644 --- a/src/Mod/Part/App/Attacher.cpp +++ b/src/Mod/Part/App/Attacher.cpp @@ -1558,7 +1558,7 @@ Base::Placement AttachEngine3D::calculateAttachedPlacement(const Base::Placement orderString ); if(this->mapReverse){ - rot = rot * Base::Rotation(Base::Vector3d(0,1,0),D_PI); + rot = rot * Base::Rotation(Base::Vector3d(0,1,0),M_PI); } Base::Placement plm = diff --git a/src/Mod/Points/App/PointsGrid.cpp b/src/Mod/Points/App/PointsGrid.cpp index 088bb165d9a20..a352b14810e72 100644 --- a/src/Mod/Points/App/PointsGrid.cpp +++ b/src/Mod/Points/App/PointsGrid.cpp @@ -804,7 +804,7 @@ bool PointsGridIterator::InitOnRay(const Base::Vector3d& rclPt, // needed in NextOnRay() to avoid an infinite loop _cSearchPositions.clear(); - _fMaxSearchArea = FLOAT_MAX; + _fMaxSearchArea = FLT_MAX; raulElements.clear(); diff --git a/src/Mod/Points/App/PointsGrid.h b/src/Mod/Points/App/PointsGrid.h index 8b80927ae4a11..dd40a1cb5a2eb 100644 --- a/src/Mod/Points/App/PointsGrid.h +++ b/src/Mod/Points/App/PointsGrid.h @@ -288,7 +288,7 @@ class PointsExport PointsGridIterator Base::Vector3d _clPt; /**< Base point of search ray. */ Base::Vector3d _clDir; /**< Direction of search ray. */ bool _bValidRay {false}; /**< Search ray ok? */ - float _fMaxSearchArea {FLOAT_MAX}; + float _fMaxSearchArea {FLT_MAX}; /** Checks if a grid position is already visited by NextOnRay(). */ struct GridElement { diff --git a/src/Mod/ReverseEngineering/Gui/Command.cpp b/src/Mod/ReverseEngineering/Gui/Command.cpp index b4cacdcd97f0b..321ec8ad5ef36 100644 --- a/src/Mod/ReverseEngineering/Gui/Command.cpp +++ b/src/Mod/ReverseEngineering/Gui/Command.cpp @@ -238,7 +238,7 @@ void CmdApproxCylinder::activated(int) fit.SetInitialValues(base, axis); } - if (fit.Fit() < FLOAT_MAX) { + if (fit.Fit() < FLT_MAX) { Base::Vector3f base, top; fit.GetBounding(base, top); float height = Base::Distance(base, top); @@ -295,7 +295,7 @@ void CmdApproxSphere::activated(int) const MeshCore::MeshKernel& kernel = mesh.getKernel(); MeshCore::SphereFit fit; fit.AddPoints(kernel.GetPoints()); - if (fit.Fit() < FLOAT_MAX) { + if (fit.Fit() < FLT_MAX) { Base::Vector3f base = fit.GetCenter(); std::stringstream str; @@ -344,7 +344,7 @@ void CmdApproxPolynomial::activated(int) const MeshCore::MeshKernel& kernel = mesh.getKernel(); MeshCore::SurfaceFit fit; fit.AddPoints(kernel.GetPoints()); - if (fit.Fit() < FLOAT_MAX) { + if (fit.Fit() < FLT_MAX) { Base::BoundBox3f bbox = fit.GetBoundings(); std::vector poles = fit.toBezier(bbox.MinX, bbox.MaxX, bbox.MinY, bbox.MaxY); diff --git a/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.cpp b/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.cpp index 37a9b3ffedf3f..90b54afe7b290 100644 --- a/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.cpp +++ b/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.cpp @@ -122,7 +122,7 @@ void FitBSplineSurfaceWidget::onMakePlacementClicked() }); MeshCore::PlaneFit fit; fit.AddPoints(data); - if (fit.Fit() < FLOAT_MAX) { + if (fit.Fit() < FLT_MAX) { Base::Vector3f base = fit.GetBase(); Base::Vector3f dirU = fit.GetDirU(); Base::Vector3f norm = fit.GetNormal(); diff --git a/src/Mod/ReverseEngineering/Gui/Segmentation.cpp b/src/Mod/ReverseEngineering/Gui/Segmentation.cpp index b28b6230fb90e..ad65ad08ac60f 100644 --- a/src/Mod/ReverseEngineering/Gui/Segmentation.cpp +++ b/src/Mod/ReverseEngineering/Gui/Segmentation.cpp @@ -115,7 +115,7 @@ void Segmentation::accept() std::vector indexes = kernel.GetFacetPoints(jt); MeshCore::PlaneFit fit; fit.AddPoints(kernel.GetPoints(indexes)); - if (fit.Fit() < FLOAT_MAX) { + if (fit.Fit() < FLT_MAX) { Base::Vector3f base = fit.GetBase(); Base::Vector3f axis = fit.GetNormal(); MeshCore::AbstractSurfaceFit* fitter = diff --git a/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp b/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp index 9e949f73dea1d..a449e7595809d 100644 --- a/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp +++ b/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp @@ -215,7 +215,7 @@ void SegmentationManual::onPlaneDetectClicked() MeshCore::PlaneFit fit; fit.AddPoints(points); - if (fit.Fit() < FLOAT_MAX) { + if (fit.Fit() < FLT_MAX) { Base::Vector3f base = fit.GetBase(); Base::Vector3f axis = fit.GetNormal(); return new MeshCore::PlaneSurfaceFit(base, axis); @@ -239,7 +239,7 @@ void SegmentationManual::onCylinderDetectClicked() Base::Vector3f axis = fit.GetInitialAxisFromNormals(normal); fit.SetInitialValues(base, axis); } - if (fit.Fit() < FLOAT_MAX) { + if (fit.Fit() < FLT_MAX) { Base::Vector3f base = fit.GetBase(); Base::Vector3f axis = fit.GetAxis(); float radius = fit.GetRadius(); @@ -259,7 +259,7 @@ void SegmentationManual::onSphereDetectClicked() MeshCore::SphereFit fit; fit.AddPoints(points); - if (fit.Fit() < FLOAT_MAX) { + if (fit.Fit() < FLT_MAX) { Base::Vector3f base = fit.GetCenter(); float radius = fit.GetRadius(); return new MeshCore::SphereSurfaceFit(base, radius); diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp b/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp index e3c84220b9686..46e41c5e4cae3 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp +++ b/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp @@ -799,7 +799,7 @@ int DrawSketchHandler::seekAutoConstraint(std::vector& suggested double angle = atan2(projPnt.y, projPnt.x); while (angle < startAngle) { - angle += 2 * D_PI;// Bring it to range of arc + angle += 2 * M_PI;// Bring it to range of arc } // if the point is on correct side of arc @@ -851,7 +851,7 @@ int DrawSketchHandler::seekAutoConstraint(std::vector& suggested 2.f * M_PI); while (angle < startAngle) { - angle += 2 * D_PI;// Bring it to range of arc + angle += 2 * M_PI;// Bring it to range of arc } // if the point is on correct side of arc diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h index 2d124c0f1fe71..5e08628c68d94 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h @@ -416,7 +416,7 @@ class DrawSketchHandlerBSpline: public DrawSketchHandler SbString text; std::string lengthString = lengthToDisplayFormat(length, 1); std::string angleString = - angleToDisplayFormat((angle != -FLOAT_MAX) ? angle * 180 / M_PI : 0, 1); + angleToDisplayFormat((angle != FLT_MIN) ? angle * 180 / M_PI : 0, 1); text.sprintf(" (%s, %s)", lengthString.c_str(), angleString.c_str()); setPositionText(position, text); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSplineByInterpolation.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSplineByInterpolation.h index bad862f56e647..315fe2d8e6f92 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSplineByInterpolation.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSplineByInterpolation.h @@ -414,7 +414,7 @@ class DrawSketchHandlerBSplineByInterpolation: public DrawSketchHandler SbString text; std::string lengthString = lengthToDisplayFormat(length, 1); std::string angleString = - angleToDisplayFormat((angle != -FLOAT_MAX) ? angle * 180 / M_PI : 0, 1); + angleToDisplayFormat((angle != FLT_MIN) ? angle * 180 / M_PI : 0, 1); text.sprintf(" (%s, %s)", lengthString.c_str(), angleString.c_str()); setPositionText(position, text); } diff --git a/src/Mod/TechDraw/App/Geometry.cpp b/src/Mod/TechDraw/App/Geometry.cpp index b0c0d300ae71c..97d41ecf31596 100644 --- a/src/Mod/TechDraw/App/Geometry.cpp +++ b/src/Mod/TechDraw/App/Geometry.cpp @@ -1162,7 +1162,7 @@ double Generic::slope() { Base::Vector3d v = asVector(); if (v.x == 0.0) { - return DOUBLE_MAX; + return DBL_MAX; } else { return v.y/v.x; } diff --git a/src/Mod/TechDraw/App/TechDrawExport.cpp b/src/Mod/TechDraw/App/TechDrawExport.cpp index ed6446fb4635c..ef644db0219b9 100644 --- a/src/Mod/TechDraw/App/TechDrawExport.cpp +++ b/src/Mod/TechDraw/App/TechDrawExport.cpp @@ -479,7 +479,6 @@ void DXFOutput::printHeader( std::ostream& out) void DXFOutput::printCircle(const BRepAdaptor_Curve& c, std::ostream& out) { gp_Circ circ = c.Circle(); - //const gp_Ax1& axis = c->Axis(); const gp_Pnt& p= circ.Location(); double r = circ.Radius(); double f = c.FirstParameter(); @@ -572,27 +571,8 @@ void DXFOutput::printEllipse(const BRepAdaptor_Curve& c, int /*id*/, std::ostrea double r2 = ellp.MinorRadius(); double dp = ellp.Axis().Direction().Dot(gp_Vec(0, 0,1)); - // a full ellipse - /* if (s.SquareDistance(e) < 0.001) { - out << ""; - } - // arc of ellipse - else { - // See also https://developer.mozilla.org/en/SVG/Tutorial/Paths - gp_Dir xaxis = ellp.XAxis().Direction(); - Standard_Real angle = xaxis.Angle(gp_Dir(1, 0,0)); - angle = Base::toDegrees(angle); - char las = (l-f > D_PI) ? '1' : '0'; // large-arc-flag - char swp = (a < 0) ? '1' : '0'; // sweep-flag, i.e. clockwise (0) or counter-clockwise (1) - out << ""; - }*/ - gp_Dir xaxis = ellp.XAxis().Direction(); - double angle = xaxis.AngleWithRef(gp_Dir(1, 0,0), gp_Dir(0, 0,-1)); - //double rotation = Base::toDegrees(angle); + gp_Dir xaxis = ellp.XAxis().Direction(); + double angle = xaxis.AngleWithRef(gp_Dir(1, 0,0), gp_Dir(0, 0,-1)); double start_angle = c.FirstParameter(); double end_angle = c.LastParameter(); @@ -655,10 +635,6 @@ void DXFOutput::printBSpline(const BRepAdaptor_Curve& c, int id, std::ostream& o return; } - //GeomConvert_BSplineCurveToBezierCurve crt(spline); - //GeomConvert_BSplineCurveKnotSplitting crt(spline, 0); - //Standard_Integer arcs = crt.NbArcs(); - //Standard_Integer arcs = crt.NbSplits()-1; Standard_Integer m = 0; if (spline->IsPeriodic()) { m = spline->NbPoles() + 2*spline->Degree() - spline->Multiplicity(1) + 2; @@ -701,7 +677,6 @@ void DXFOutput::printBSpline(const BRepAdaptor_Curve& c, int id, std::ostream& o } } - //str << "\" />"; out << str.str(); } catch (Standard_Failure&) {